11
votes

I'm using @vue/cli 3.x and in my vue.config.js I have this:

devServer: {
    proxy: {
      "/api": {
        ws: true,
        changeOrigin: true,
        target: "http://localhost:8080"
      }
    }
  }

But I keep getting CORS error:

Access to XMLHttpRequest at 'http://localhost:8080/api' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any idea?

1
I'm no CORS expert, but if I were to guess I'd say you need to enable CORS from your server and add Access-Control-Allow-Origin to your request header. It's your server complaining, not your Vue frontend.James Whiteley
@JamesWhiteley - that is exactly why I define a proxy, so I don't need to define CORS on my serverTomer
@Tomer: did you ever find a solution to this problem?dotNET
@dotNET - actually yes :), apparently I had some Axios configurations that were ignoring the proxy. my dev server config looks like this: devServer: { proxy: { "^/api": { target: url, ws: true, changeOrigin: true } } },Tomer

1 Answers

11
votes

It looks like the problem was with the axios configurations.

I had this definition: axios.defaults.baseURL = "http://localhost:8080/api"; I changed it to axios.defaults.baseURL = "api";

and it works.

module.exports = {
    ...
    devServer: {
        proxy: {
          "^/api": {
          target: url,
          ws: true,
          changeOrigin: true
        }
     }
  },
}