如何解决对Express服务器做出反应的Axios POST请求返回404
我在我的react-app中使用Axios。 在服务器端口3000上运行react应用,在端口31001上运行Express服务器
我的反应组件-
import React from 'react';
import {Form,Button} from 'react-bootstrap';
import { Link,useHistory } from 'react-router-dom';
import Axios from "axios";
export default function Register(){
let history = useHistory();
function signMeUp(e){
e.preventDefault()
let userName = document.getElementById('username')?.value
let password = document.getElementById('password')?.value
let data = {
userName:document.getElementById('username')?.value,password:document.getElementById('password')?.value,}
Axios({
method: "POST",url: "http://localhost:31001/register",data,headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res.data.message);
});
console.log(userName,password)
if(userName && password){
history.push("/Login");
}
else{
alert('Enter a username / password')
}
}
return(
<div style={{width:"50vw",margin:"auto",marginTop:"50px"}}>
<h1 style={{textAlign:"center",paddingBottom:"30px"}}>Book My Movie</h1>
<h1 style={{textAlign:"center"}}>Register</h1>
<Form onSubmit={(e)=>{signMeUp(e)}}>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" id="username" />
<Form.Text className="text-muted">
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Password" id="password" />
</Form.Group>
<Button variant="primary" type="submit" style={{width:"100%"}}>
Submit
</Button>
<div style={{textAlign:"center",margin:"auto"}}>
<Link to="/Login">Already have a account ? Login Here</Link>
</div>
</Form>
</div>
);
}
我的server.js
const express = require("express"),app = express(),port = process.env.PORT || 31001,cors = require("cors");
app.use(cors());
app.listen(port,() => console.log("Backend server live on " + port));
app.get("/register",(req,res) => {
res.send({ message: "We did it!" });
});
我还在package.json上放置了一个代理::
"proxy": "http://localhost:31001",
这是我在Chrome控制台上收到的错误:
xhr.js:184 POST http://localhost:31001/register 404 (Not Found)
createError.js:16 Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:69)
我已经阅读了几乎所有的stackoverflow解决方案,但没有为我工作。
解决方法
方法应为post
中的app.post("/register",(req,res) => { ..
因为我在前端,您正在做 method: "POST",
:
Axios({
method: "POST",url: "http://localhost:31001/register",data,headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res.data.message);
});
,
您正在请求POST
,但是您正在听GET
请求。您必须将快速路由更改为发布请求侦听器。
在这种情况下,您将可以获取请求正文,而不是←(如果正在发送) :
app.post("/register",res) => { //<---change to post
res.json({ message: "We did it!" }); // <----res.json to send data as json.
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。