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': ''      }    }  },

這樣就可以請求成功了。