Vue devServer proxy is not helping, I still get CORS error
Asked Answered
K

1

13

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?

Kellyekellyn answered 10/4, 2019 at 7:46 Comment(4)
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.Time
@JamesWhiteley - that is exactly why I define a proxy, so I don't need to define CORS on my serverKellyekellyn
@Tomer: did you ever find a solution to this problem?Yardley
@Yardley - 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 } } },Kellyekellyn
K
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
        }
     }
  },
}
Kellyekellyn answered 19/10, 2019 at 16:24 Comment(3)
In what file do you exactly add this axios.defaults.baseURL = "api" ?Uigur
I have axios.config.js file which i import in my main file, but it doesn't really matter what you name itKellyekellyn
Yup, this was very useful. Thanks a lotHueston

© 2022 - 2024 — McMap. All rights reserved.