react设置跨域代理
在src文件夹下新建setProxy.js文件
setProxy.js:
const { createProxyMiddleware } = require('http-proxy-middleware')
module.exports= function (app) {
app.use(
createProxyMiddleware(
"/api",
{
target: "http://127.0.0.1:8080",
changeOrigin: true,
ws: true,
pathRewrite:{
"^/api":"",
},
}
)
)
}
还要记得安装http-proxy-middleware模块:
npm install http-proxy-middleware
react项目启动后,Localhost页面拒绝访问的原因
Localhost页面拒绝访问,多半是因为setupProxy设置跨域代理时出现了错误,只要写法对了就不会出错。高版本引入方式:
const { createProxyMiddleware } = require('http-proxy-middleware')
还要特别注意下面一行函数的写法:
module.exports= function (app) {...}
React项目运行出现错误:When specified, “proxy” in package.json must be a string.Instead, the type of “proxy” was “object”.Either remove “proxy” from package.json, or make it a string.
原因
如果只是在代理中使用纯字符串,则不需要任何其他配置。但是,当您使用对象时,您正在使用高级配置。这个错误是因为在配置代理时直接在package.json中添加了:
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
}
}
因此,解决步骤如下:
-
安装http-proxy-middleware:
npm i --save http-proxy-middleware
-
从package.json中删除代码:
"proxy": { "/auth/google": { "target": "http://localhost:5000" } }
-
为代理创建一个安装文件。在客户端的src文件夹中,创建文件setupProxy.js,然后输入以下代码:
const proxy = require('http-proxy-middleware'); module.exports = function(app) { app.use(proxy('/auth/google', { target: 'http://localhost:5000/' } )); }
-
上述代码可能会出现错误:Localhost页面拒绝访问,这是因为引入方式版本太低,高版本引入方式:
const { createProxyMiddleware } = require('http-proxy-middleware')
-
完整代码
const { createProxyMiddleware } = require('http-proxy-middleware') module.exports= function (app) { app.use( createProxyMiddleware( "/api", { target: "http://127.0.0.1:8080", changeOrigin: true, ws: true, pathRewrite:{ "^/api":"", }, } ) ) }