浏览器出现报错:crbug/1173575, non-JS module files deprecated
React脚手架 采用setupProxy.js实现跨域,浏览器出现crbug/1173575, non-JS module files deprecated报错
一、问题描述
最近学习react,教程中讲解使用setupProxy.js文件配置跨域代理,按照教程的写法出现了问题,可能是http-proxy-middleware版本问题导致找不到模块
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
proxy('/api1', { //遇见/api1前缀的请求,就会触发该代理配置
target: 'http://localhost:5000', //请求转发给谁
changeOrigin: true,//控制服务器收到的请求头中Host的值
pathRewrite: { '^/api1': '' } //重写请求路径(必须)
}),
proxy('/api2', {
target: 'http://localhost:5001',
changeOrigin: true,
pathRewrite: { '^/api2': '' }
}),
)
}
二、解决方法
上面的写法是http-proxy-middleware版本0.x的写法,已经被淘汰
现在使用的是createProxyMiddleware模块,写法如下
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
createProxyMiddleware('/api1', {
//api1是需要转发的请求(所有带有/api1前缀的请求都会转发给5000)
target: 'http://localhost:5000', //配置转发目标地址(能返回数据的服务器地址)
changeOrigin: true, //控制服务器接收到的请求头中host字段的值
pathRewrite: { '^/api1': '' }, //去除请求前缀,保证交给后台服务器的是正常请求地址(必须配置)
}),
createProxyMiddleware('/api2', {
target: 'http://localhost:5001',
changeOrigin: true,
pathRewrite: { '^/api2': '' },
})
)
}