項目基於Vue前端+Node后台,啟動兩個服務,請求數據時,端口不一致造成跨域報錯:
(No 'Access-Control-Allow-Origin' header is present on the requested resource)
經過查官方API得到以下兩種思路:
1、在Node后台中設置,允許訪問
1.1、用代碼控制
app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://localhost:8080"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","POST,GET"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next(); });
1.2、安裝Core包,例如:
npm install cors --save
const cors = require('cors')
app.use(
cors({
origin: ['http://localhost:8080'], //前端地址
methods: ['GET', 'POST'],
alloweHeaders: ['Conten-Type', 'Authorization']
})
)
但,若之前遇到后台不是自己開發的接口,而是第三方接口,例如,Google,這樣就無法從服務器設置入手。
2、在vue.config.js中進行代理配置:(proxy)
proxy: { // 配置跨域 '/api': { target: 'http://localhost:3001/', ws: true, changOrigin: true, pathRewrite: { '^/api': '' } } },
在頁面調用的時候,用api代替 http://localhost:3001/
axios.get('api/test/fscontent') //調用了http://localhost:3001/test/fscontent接口
.then(response => {
console.log(response.data)
})