前言
我們在使用vue-cli啟動項目的時候npm run dev
便可以啟動我們的項目了,通常我們的請求地址是以localhost:8080來請求接口數據的,localhost是沒有辦法設置cookie的。
我們可以在vue-cli配置文件里面設置一個代理,跨域的方法有很多,通常需要后台來進行配置。我們可以直接通過node.js代理服務器來實現跨域請求。
vue proxyTable接口跨域請求調試
在vue-cli項目中的config
文件夾下的index.js
配置文件中,dev
長這樣子:
dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, cssSourceMap: false }
服務器提供的接口如果長這樣https://www.exaple.com/server_new/login
,我們把域名提取出來如https://www.exaple.com
;
在config中新建一個文件命名為proxyConfig.js
:
module.exports = { proxy: { '/apis': { //將www.exaple.com印射為/apis target: 'https://www.exaple.com', // 接口域名 changeOrigin: true, //是否跨域 pathRewrite: { '^/apis': '' //需要rewrite的, } } } }
config
文件夾下的index.js
引入proxyConfig.js
:
var proxyConfig = require('./proxyConfig')
config
文件夾下的index.js
中的dev
改成:
dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: proxyConfig.proxy, cssSourceMap: false }
重啟項目npm run dev
:
你會發現出現了這個
這個時候我們已經設置好了本地API代理了
修改本地hosts
文件
文件路徑一般是C:\Window\System32\drivers\etc
,打開hosts
文件,在這一段下面把localhost
設置進去
# localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost 127.0.0.1 activate.adobe.com 127.0.0.1 practivate.adobe.com 127.0.0.1 lmlicenses.wip4.adobe.com 127.0.0.1 lm.licenses.adobe.com 127.0.0.1 na1r.services.adobe.com 127.0.0.1 hlrcv.stage.adobe.com localhost www.exaple.com