Vue webpack项目配置请求接口,修改代理,解决跨域问题

  • 2020 年 3 月 17 日
  • 筆記

在写项目的时候,经常会遇到一些请求和跨域问题。

比如接口请求不到:Uncaught (in promise) Error: Request failed with status code 404 或者 http://localhost:8081/list 404 (Not Found)

跨域问题:Access to XMLHttpRequest at 'loaclhost:3000/list' from origin 'http://localhost:8081' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. 等。

这时候我们可以修改一些 Vue 项目的配置,添加代理,解决接口请求不到或者跨域问题。

找到项目文件夹下的 /config/index.js 文件,添加如下配置:

proxyTable: { // 设置代理    '/api': {      target: 'http://localhost:3000',  // 后台接口地址      ws: true,        // 如果要代理 websockets,配置这个参数      secure: false,  // 如果是https接口,需要配置这个参数      changeOrigin: true,  // 是否跨域      pathRewrite: {        '^/api': ''      }    }  },

这样就可以请求成功了。