使用devServer解决跨域问题
在开发阶段很多时候需要使用到跨域,何为跨域?请看下图:
图片1
跨域问题的出现主要是由于浏览器的安全机制同源策略,使用http proxy是借用webpack-server服务器转发到接口服务器,这样避开了浏览器的同源策略问题,变成两个服务器间的交互,从而解决跨域问题。
开发阶段往往会遇到上面这种情况,也许将来上线后,前端项目会和后端项目部署在同一个服务器下,并不会有跨域问题,但是由于开发时会用到webpack-dev-server,所以一定会产生跨域的问题
目前解决跨域主要的方案有:
- jsonp(淘汰)
- cors(最主流)
- http proxy
此处介绍的使用devServer解决跨域,其实原理就是http proxy
将所有ajax请求发送给devServer服务器,再由devServer服务器做一次转发,发送给数据接口服务器
由于ajax请求是发送给devServer服务器的,所以不存在跨域,而devServer由于是用node平台发送的http请求,自然也不涉及到跨域问题,可以完美解决!
图片2
模拟cors
服务器代码(返回一段字符串即可):
安装
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中进行配置:
devServer: {
open: true,
hot: true,
compress: true,
port: 3000,
// contentBase: './src'
proxy: {
'/api': 'http://localhost:9999'
}
},
意为前端请求/api的url时,webpack-dev-server会将请求转发给 http://localhost:9999/api
处,此时如果请求地址为http://localhost:9999/api/getUserInfo
,只需要直接写/api/getUserInfo
即可,如下:
axios.get('/api/getUserInfo')
.then(result => console.log(result))
如果服务器地址都是一级域名,前面并没有统一的/api,可以增加pathRewrite更简便;此时如果请求地址为http://localhost:9999/api/getUserInfo
,服务器会转发为http://localhost:9999/getUserInfo
,代码如下:
proxy: {
'/api': {
target:'http://localhost:9999',
pathRewrite:{
'^/api':''
}
}
}
仅适用于开发环境,生产环境中需要把代码和服务器代码部署到一起,否则也可以通过Nginx进行跨域的转发。
网友评论