12

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?

Tomer
  • 17,787
  • 15
  • 78
  • 137
  • 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 Apr 10 '19 at 09:14
  • @JamesWhiteley - that is exactly why I define a proxy, so I don't need to define CORS on my server – Tomer Apr 10 '19 at 10:16
  • @Tomer: did you ever find a solution to this problem? – dotNET Oct 18 '19 at 12:19
  • 1
    @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 Oct 19 '19 at 16:14

1 Answers1

13

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
        }
     }
  },
}
Tomer
  • 17,787
  • 15
  • 78
  • 137