I'm trying to build a very basic full stack application with React and Node. I'm having trouble getting the front end to send the data to the server. I'm getting POST http://localhost:4000/ 500 (Internal Server Error)
in my console. What do I need to do to send the data submitted by the user to the server so I can store it in a database?
My react code
class App extends React.Component {
constructor() {
super();
this.state = {text: ''}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(e) {
e.preventDefault();
fetch('http://localhost:4000/users', {
method: "POST",
headers: {"Content-Type": "application/json"},
body: this.state.text // trying to send this text to the server
})
.then((response) => {
console.log('success writing to server', response)
})
.catch((err) => {
console.log('error writing to server', err);
})
}
handleChange(e) {
this.setState({
text: e.target.value
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input onChange={this.handleChange} type="text" placeholder="Name" ref="name" />
<input type="submit" />
</form>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
My server code:
const express = require('express');
const mysql = require('mysql');
const port = process.env.port || 4000;
const app = express();
let db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'my_db'
})
app.use(express.static('public'));
app.post('/users', function (req, res) {
console.log(req.body) // undefined
// I would have thought that req.body.text would work but req.body is undefined
db.query(`INSERT INTO users (user) VALUES ("${req.body.text}")`, function (err, result) {
if (err) {
console.log('error inserting into database', err.sqlMessage);
} else {
console.log('successful insertion into database', result);
}
});
res.sendStatus(201);
});
app.listen(port, 'localhost');
By specifying "Content-Type": "application/json"
in your request, you are telling your server that it is going to receive a JSON object.
However, the body that you are sending is this.state.text
which is the raw value in your input, a string, not a JSON, this is why your server sees it as undefined.
You first need to put it in a JSON, and then stringify it before sending it to your server :
fetch('http://localhost:4000/users', {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({ textInput: this.state.text })
})
Another way around could be to tell the server that it is going to receive raw text :
fetch('http://localhost:4000/users', {
method: "POST",
headers: {"Content-Type": "text/plain"}, //Expects a raw text body
body: this.state.text
})
You can see a more precise explanation of how to use fetch in the following documentation : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Your Express server seems to be missing body parser middleware. Add this before your route handlers:
app.use(express.json())
Also in general you need to pass the body to JSON.stringify()
when making a fetch
request client-side.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.