问题
I'm writing program that uses React as front-end, and an Express/Node API for the backend which then does CRUD operations in a MongoDB database. Right now, I'm using the native JS fetch() API to perform GET/POST operations on my front end. The GET requests work just fine, but my POST requests seem to not be working. On my front end, I have a form and a handler for form submission like so:
handleSubmit(){
let databody = {
"name": this.state.nameIn,
"quote": this.state.quoteIn
}
return fetch('http://localhost:5002/stored', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Name
<input type="text" name="name" value={this.nameIn} onChange={this.handleNameChange}/>
</label>
<label>
quote
<input type="text" name="quote" value={this.quoteIn} onChange={this.handleQuoteChange}/>
</label>
<input type="submit" value="Add to DB" />
</form>
</div>
);
}
Then on my Express API, which is on port 5002, I have:
app.post('/stored', (req, res) => {
console.log(req.body);
db.collection('quotes').insertOne(req.body, (err, data) => {
if(err) return console.log(err);
res.send(('saved to db: ' + data));
})
});
However, when the form is submitted, the request shows up on the Express API with an empty body. The console.log shows that req.body is just an { } I'm wondering what I did wrong?
回答1:
use body-parser
in your express code add :
global.bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 100000
}))
app.use(bodyParser.json({
limit: '50mb',
parameterLimit: 100000
}))
app.post('/stored', (req, res) => {
console.log(req.body);
db.collection('quotes').insertOne(req.body, (err, data) => {
if(err) return console.log(err);
res.send(('saved to db: ' + data));
})
});
in your froontend :
handleSubmit:function(e){
e.preventDefault();
let databody = {
"name": this.state.nameIn,
"quote": this.state.quoteIn
}
fetch('http://localhost:5002/stored', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
回答2:
If you use express 4.16 or later you can just use express.json(), it will attempt to parse the JSON of the request body and save it to req.body, but only if the header "Content-Type: application/json" is sent along with the request:
const app = express();
app.use(express.json()); // Parses request body if type is json. Saves to req.body.
来源:https://stackoverflow.com/questions/50617351/react-post-requests-with-express-node-and-mongodb