I am not very sure why this isn't working. I am trying to post from react to express using axios. I followed a tutorial on connecting react frontend to express server and it works for fetching data from server with a proxy. However, when I try to post data from react to the server, it does not work. I was prompted with two uncaught errors (cannot see them due to refresh) and then the page immediately refreshed with the form response posted to the url of the original react page instead of redirecting and posting to the server page with the form data.
client/package.json
{
"name": "syllabus.io",
"version": "0.1.0",
"proxy": "http://localhost:8000/",
...
client/Login.js
import '../App.css';
import React, {useState} from 'react';
import axios from 'axios';
function Login() {
const [data, setData] = useState({
email: "",
password: ""
});
function handleLogin(e) {
e.preventDafault();
console.log(data.email, data.password);
axios
.post('http://localhost:8000/api/login-post', data)
.then(() => console.log('Book Created'))
.catch(err => {
console.error(err);
});
}
function handleInput(e) {
const newData={...data};
newData[e.target.id] = e.target.value;
setData(newData);
}
return (
<div id="login" className="login">
<body>
<h1 id="title">Login</h1>
<div >
<form onSubmit={(e) => handleLogin(e)}>
<input type="text" onChange={(e) => handleInput(e)} className="email" name="email" value={data.email} id="email" placeholder="Email"/>
<input type="text" onChange={(e) => handleInput(e)} className="password" name="password" value={data.password} id="password" placeholder="Password"/>
<input id="Login" className="Login" type="submit" value="Login"/>
</form>
</div>
</body>
</div>
);
}
export default Login;
server/server.js
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get("/api", (req, res) => {
res.json({"user": ["userOne", "userTwo", "userThree"]})
})
app.post("/api/login-post", (req, res) => {
console.log(req.body)
res.send("Success")
})
app.listen(8000, () => {console.log('Server started on port 8000...')})
Edit: The error, after checking preserve log, is
CodePudding user response:
There is a typo in e.preventDefault(); in handleLogin function thus your form is submitted without a payload. I hope this fixes it.