내 반응 앱에서 Axios를 사용하고 있습니다. 서버 포트 3000에서 반응 앱 실행 및 포트 31001에서 익스프레스 서버 실행
내 반응 구성 요소-
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",
이것은 크롬 콘솔에서받는 오류입니다.
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);
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다