devServer proxy in config throws 404

*爱你&永不变心* 提交于 2020-12-10 08:21:15

问题


I have this in src/vue.config.js

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8081',
        changeOrigin: true,
      },
    },
  },
};

and I'm calling the api with

  axios.get('/api/parts')
    .then(result => commit('updateParts', result.data))
    .catch(console.error);

But I just keep getting

Error: "Request failed with status code 404"

And I can see the request is being made to port 8080 instead of 8081

I can access the api in the browser with no problems

How can I debug this?


回答1:


Your vue.config.js is not supposed to be in the src folder. It must be in the root of your project. Simply move the file.

The configuration reference for the server can be found here: https://cli.vuejs.org/config/#devserver-proxy but it seems you're actually doing it right. The file is just at the wrong folder.




回答2:


I had the same issue after trying a couple of combinations finally I figured it out.

I am using Axios and my application is running at port 8080

main.js:

axios.defaults.baseURL = 'http://localhost:8080/api/'

vue.config.js

module.exports = {
    devServer: {
      proxy: 'https://reqres.in'
    }
}

My Vue Component

this.axios.get("users")
   .then(response => {
    this.items = response.data.data;
    this.isLoading = false;
})

Browser's Network tab:




回答3:


it is not right, if you use proxy, your remote address must be same as request url and port, so your vue.config.js should be edited like below:

proxy: {
          '/api': {
              target: 'http://localhost:8080',
              changeOrigin: true
          }

or you can use rewrite attribute like this :

proxy: {
          '/api': {
              target: 'http://localhost:8080',
              changeOrigin: true,
              pathRewrite: { '^/api': '/'}
          }
      }

the difference is the real request, top will be http://localhost:8080/api/..., rewrite will be http://localhost:8080/...



来源:https://stackoverflow.com/questions/54216516/devserver-proxy-in-config-throws-404

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!