在开发阶段很多时候需要使用到跨域。
目前解决跨域主要的方案有:
- jsonp (逐渐淘汰)
- cors (主流)
- http proxy
devServer解决跨域,其实原理就是http proxy。
将所有ajax请求发送给devServer服务器,再由devServer服务器做一次转发,发送给数据接口服务器。
由于ajax请求是发送给devServer服务器的,所以不存在跨域,而devServer由于是用node平台发送的http请求,自然也不涉及跨域问题,可以完美解决。
服务器端代码(返回一段字符串即可)
const express = require('express')
cosnt app = express()
// const cors = require('cros')
// app.use(cors())
app.get('/api/getUserInfo', (req, res) => {
res.send({
name: 'Mango',
age: 18
})
})
app.listen(9999)
前端配置
前端需要配置 devServer 的 proxy 功能,在 webpack.dev.js 中进行配置:
devServer: {
open: true,
hot: true,
compress: true,
proxy: {
// 当请求 /api/getUserInfo 时,会转发为 http://localhost:9999/api/getUserInfo
'/api': 'http://localhost:9999',
// 第二种配置方式
// target 目标
// pathRewrite 对路径进行重写
'/api': {
target: 'http://localhost:9999',
pathRewire: {
'^/api': '' // 当请求/api/getUserInfo 时,会转发为 http://localhost:9999/getUserInfo
}
}
}
}