使用devServer解決跨域問題
在開發(fā)階段很多時(shí)候需要使用到跨域,何為跨域?請(qǐng)看下圖:
圖片1
跨域問題的出現(xiàn)主要是由于瀏覽器的安全機(jī)制同源策略,使用http proxy是借用webpack-server服務(wù)器轉(zhuǎn)發(fā)到接口服務(wù)器,這樣避開了瀏覽器的同源策略問題,變成兩個(gè)服務(wù)器間的交互,從而解決跨域問題。
開發(fā)階段往往會(huì)遇到上面這種情況,也許將來上線后,前端項(xiàng)目會(huì)和后端項(xiàng)目部署在同一個(gè)服務(wù)器下,并不會(huì)有跨域問題,但是由于開發(fā)時(shí)會(huì)用到webpack-dev-server,所以一定會(huì)產(chǎn)生跨域的問題
目前解決跨域主要的方案有:
- jsonp(淘汰)
- cors(最主流)
- http proxy
此處介紹的使用devServer解決跨域,其實(shí)原理就是http proxy
將所有ajax請(qǐng)求發(fā)送給devServer服務(wù)器,再由devServer服務(wù)器做一次轉(zhuǎn)發(fā),發(fā)送給數(shù)據(jù)接口服務(wù)器
由于ajax請(qǐng)求是發(fā)送給devServer服務(wù)器的,所以不存在跨域,而devServer由于是用node平臺(tái)發(fā)送的http請(qǐng)求,自然也不涉及到跨域問題,可以完美解決!
圖片2
模擬cors
服務(wù)器代碼(返回一段字符串即可):
安裝
npm i cors -S
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
app.get('/api/getUserInfo', (req, res) => {
res.send({
name: '1111',
age: 13
})
});
app.listen(9999, () => {
console.log('http://localhost:9999');
});
http proxy
前端需要配置devServer的proxy功能,在webpack.dev.js中進(jìn)行配置:
devServer: {
open: true,
hot: true,
compress: true,
port: 3000,
// contentBase: './src'
proxy: {
'/api': 'http://localhost:9999'
}
},
意為前端請(qǐng)求/api的url時(shí),webpack-dev-server會(huì)將請(qǐng)求轉(zhuǎn)發(fā)給 http://localhost:9999/api處,此時(shí)如果請(qǐng)求地址為http://localhost:9999/api/getUserInfo,只需要直接寫/api/getUserInfo即可,如下:
axios.get('/api/getUserInfo')
.then(result => console.log(result))
如果服務(wù)器地址都是一級(jí)域名,前面并沒有統(tǒng)一的/api,可以增加pathRewrite更簡(jiǎn)便;此時(shí)如果請(qǐng)求地址為http://localhost:9999/api/getUserInfo,服務(wù)器會(huì)轉(zhuǎn)發(fā)為http://localhost:9999/getUserInfo,代碼如下:
proxy: {
'/api': {
target:'http://localhost:9999',
pathRewrite:{
'^/api':''
}
}
}
僅適用于開發(fā)環(huán)境,生產(chǎn)環(huán)境中需要把代碼和服務(wù)器代碼部署到一起,否則也可以通過Nginx進(jìn)行跨域的轉(zhuǎn)發(fā)。