node.js - setupProxy 不工作 - http-proxy-middleware
问题描述
我的反应应用程序在 localhost:3000 上运行,节点服务器在 localhost:5000 上运行。当我尝试连接到 express API 时,路由将转到 'localhost:3000/auth/google' 而不是 localhost:5000/auth/google
用户操作.js
export const updateLoginUser = (userData, scheme) => async dispatch => {
console.log(scheme);
if(scheme === 'google') {
// TODO: fetch user from the DB
const fetchedUser = await axios.post('/auth/google');
dispatch({
type: UPDATE_USER,
payload: fetchedUser.data
})
} else {
// TODO: fetch user from the DB
const fetchedUser = await axios.post('/api/get_user/', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(userData)
})
dispatch({
type: UPDATE_USER,
payload: fetchedUser.data
})
}
}
setupProxy.js
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
app.use(proxy('/auth/google', { target: 'http://localhost:5000' }))
}
节点服务器.js
const express = require('express');
const mongoose = require('mongoose');
const keys = require('./config/keys');
const cookieSession = require('cookie-session');
const passport = require('passport');
const cors = require('cors');
const morgan = require('morgan');
require('./models/Users');
require('./services/passport'); // it is not returing anything hence no need of assigning
mongoose.connect(keys.mongoDBURI, { useNewUrlParser: true, useUnifiedTopology: true });
const app = express();
app.use(cors());
// Setup the cookie session
app.use(cookieSession({
maxAge: 30 * 24 * 60 * 1000, // Time till the cookie will be alive
keys: [keys.cookieKey]
}));
app.use(morgan('combined'));
// Make passport know to use the cookieSession
app.use(passport.initialize());
app.use(passport.session());
require('./routes/authRoutes')(app); // authRoute returing a function and we are immediatly invoking that function
const PORT = process.env.PORT || 5000;
app.listen(5000);
编辑:反应 package.json
{
"name": "blogpost-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.19.0",
"http-proxy-middleware": "^0.20.0",
"node-sass": "^4.13.0",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-scripts": "3.2.0",
"redux": "^4.0.4",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000"
}
我是新手,因此我不知道代理的工作原理。
解决方案
你可能需要重写你的 setupProxy.js 如下
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
然后进行 npm 安装。
在我的情况下,解决了这个问题。在这里你可以看到更多细节https://create-react-app.dev/docs/proxying-api-requests-in-development/ 还有它被提到注意:这个文件只支持 Node 的 JavaScript 语法。确保只使用受支持的语言功能(即不支持 Flow、ES 模块等)。
推荐阅读
- c++ - 从父类的相同方法调用派生类方法
- node.js - 如何配置 node-fetch 以使用公司代理?
- ssl - 当我配置多个网关时,带有 Istio 和 SDS 的 HTTPS 入口不起作用(返回 404)
- javascript - 从 React 前端 POST 到 API 不起作用——错误 400
- java - 当用户再次打开底部工作表对话框时,如何显示以前检查的项目?
- android - Dagger Android 和范围
- c# - 带位图的文件流
- .net-core - 挂火服务器变为零
- ios - 应用程序崩溃:NSInvalidArgumentException - 操作已在队列中排队
- android - 无法为 com.android.build.gradle.internal.dsl.NdkOptions 类型的对象获取未知属性“arm64-v8a”