近期重新搭建了一个react脚手架项目,因为是前后端分离开发的,所以前后端的交互因为端口不同而产生跨域,过去通常是使用配置http-proxy-middleware
中间间来处理跨域,在src
目录下新建setupProxy.js
文件,并写入以下代码,即可实现跨域:
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(proxy('/_api', {
target: 'http://localhost:8080/',
changeOrigin: true,
pathRewrite: {
"^/_api": "/"
}
}))
}
但是这次将这个文件复制到新项目下,启动项目时却发生了报错:
错误是proxy is not a function
。
查看文档之后发现官方文档的写法居然变了。。。官方在1.0.0
版本后废弃了proxy
方法,改为使用createProxyMiddleware
。对应写法为:
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
'/_api',
createProxyMiddleware({
target: 'http://localhost:8080/',
changeOrigin: true,
pathRewrite: {
"^/_api": "/"
}
})
)
}
参考资料: