[英]Axios POST request returns 404 error when sending to Node.js API
I am developing a web application using a React frontend and a Node.js backend.我正在使用 React 前端和 Node.js 后端开发 Web 应用程序。 The frontend sends a POST request to the backend using Axios like this:
前端使用 Axios 向后端发送 POST 请求,如下所示:
Register.js
...
handleSubmit = (e) => {
e.preventDefault();
const { email, password, name, dateofbirth } = this.state;
const user = { email, password, name, dateofbirth };
const url = "http://localhost:9000/register";
axios
.post(url, user, {
headers: {
"Content-Type": "application/json",
},
})
.then((response) => console.log(response))
.catch((error) => {
console.error("You have made a big error. " + error);
console.log(user);
});
};
...
While the backend receives the request like this:虽然后端收到这样的请求:
./routes/register.js
...
router.post("/register", async (req, res) => {
console.log("Inside Home Login");
res.writeHead(200, {
"Content-Type": "application/json",
});
console.log("Users : ", JSON.stringify(users));
res.end(JSON.stringify(users));
})
...
However I get the error "POST http://localhost:9000/register 404 (Not Found)" upon trying to send anything.但是,我在尝试发送任何内容时收到错误“POST http://localhost:9000/register 404 (Not Found)”。
My guess would be that you are routing in your index.js.我的猜测是您正在 index.js 中进行路由。 If you can provide a code sample to figure it out.
如果您可以提供代码示例来弄清楚。
If so, the thing is defining a routing like,如果是这样,事情就是定义一个路由,比如,
app.use('/register', yourImportedVariable);
does define a route at http://localhost:9000/register.确实在 http://localhost:9000/register 定义了一个路由。
So, if in your routes/register.js file you define a GET endpoint with '/register' your front-end call must be http://localhost:9000/register/register因此,如果在您的routes/register.js文件中定义了一个带有“/register”的 GET 端点,您的前端调用必须是http://localhost:9000/register/register
To fix it, either rename your route as '/', or fix your front-end call with the above url.要修复它,请将您的路由重命名为“/”,或者使用上述 url 修复您的前端调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.