using node 9, and express 4. I cannot seem to get the body data shown. After checking other questions, most seem to be resolved using bodyParser.urlencoded
, but that doesn't seem to help me. What am I doing wrong?
server.js
const express = require('express');
const app = express();
var bodyParser = require('body-parser');
//not sure if i need urlencoded when just sending data from client
// app.use(bodyParser.urlencoded({ extended: false }))
// app.use(bodyParser.urlencoded({ extended: true}));
// app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
const port = process.env.PORT || 8000;
const Cat = require('./Cat');
const Dog = require('./Dog');
app.route('/animals')
.get(function (req, res) {
console.log(res.body);
res.send({ Cat, Dog });
})
.patch(function (req, res) {
console.log('patch is working!');
console.log(req.body);
})
app.listen(port, () => console.log(`Listening on port ${port}`));
call in react looks like this, for now I'm just trying to get patch to show data. the get call works, and console.log 'patch is working' shows fetch is also being called, but there is no data on the body being shown.
client call
fetch('/animals', { method: 'PATCH', body: {name: 'kitten'} })
bodyParser.json()
will only parse a body when the Content-Type
of the request matches the parser you are using, which in this case would be application/json
.
Your request to your PATCH
endpoint needs to include the Content-Type
in the request.
To make request to be treated as JSON from react do so.
fetch('/animals', {
method: 'PATCH', // POST
headers: {'Content-Type':'application/json'},
body: {
"first_name": 'kitten'
} })
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.