【发布时间】:2020-12-18 17:36:57
【问题描述】:
我在我的 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 解决方案,但没有为我工作。
【问题讨论】:
标签: node.js reactjs express post axios