为什么我的后端代理(使用setupProxy.js文件进行设置)没有代理到正确的端口



我按照本指南手动设置了一个代理:https://stackoverflow.com/a/70413065/17568254,并将setupProxy.js文件放在前端的src文件夹中。我在setupProxy.js文件中有以下内容(注意target: 'http://localhost:8000'(:

const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
);
};

我在运行npm start时也会收到此消息。当我从前端对代理进行此api调用时

const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstName: firstName,
lastName: lastName,
university: university,
email: email,
password: password
}),
};
let url = '/api/add_new_user';
fetch(url, requestOptions);
.then(response => {
if (response.ok) {
handleNavigate("/Home");
}
else {
handleNavigate("/");
//do something else
}
});

在chrome-devtools中,它显示它正在对localhost:3000而不是localhost:8000进行api调用。这是我的package.json文件:

{
"name": "lawma_app",
"version": "0.1.0",
"private": true,
"dependencies": {
"5": "^0.0.1",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"bootstrap": "^5.1.3",
"firebase": "^9.9.0",
"http-proxy-middleware": "^2.0.6",
"node-sass": "^7.0.1",
"react": "^18.2.0",
"react-bootstrap": "^2.4.0",
"react-dom": "^18.2.0",
"react-resizing-pane": "^1.1.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

最后,这是我的文件结构(正如我已经提到的,setupProxy.js在src文件夹中(为什么我的React应用程序没有正确地代理到localhost:8000?

编辑:我添加了完整的api获取调用。它在Postman中工作,但在localhost中不工作,尽管使用相同的头和所有内容进行调用。我非常感谢任何关于为什么会这样的提示。

因为它调用localhost:3000,然后您的代理调用localhost:8000,所以代理就是这样工作的。

最新更新