vue項目中使用proxy解決跨域


在使用vue開發項目的時候,總會遇到跨域問題,可以在打包的時候使用proxy反向代理解決跨域問題。

vue-cli2配置如下:

找到config文件夾下的index.js

dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://moby.xbotech.com',
        changeOrigin: true,
        secure: false,
        pathRewrite: {
          '^/api': ''
        }
      }
},

vue-cli3版本以上,需要自己創建vue.config.js文件,在這個文件中自己配置

module.exports = {
    devServer: {       host: '0.0.0.0', // 允許外部ip訪問
        port: 9080, // 端口
        https: false, // 啟用https
        proxy: {
          '/api': {
            target: 'http://moby.xbotech.com/api/login',
            changeOrigin: true,
            secure: false,
            pathRewrite: {
              '^/api': '/api'
            }
          }
        }
    }
}

使用axios發送請求

aixos.get('/api/list')

總結:無論是那種方式創建的項目, '/api' 為匹配項,target 為被請求的地址,因為在 ajax 的 url 中加了前綴 '/api',而原本的接口是沒有這個前綴的,所以需要通過 pathRewrite 來重寫地址,將前綴 '/api' 轉為 '/'。如果本身的接口地址就有 '/api' 這種通用前綴,就可以把 pathRewrite 刪掉。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM