简体   繁体   English

人体解析器不起作用?

[英]Body-parser not working?

using node 9, and express 4. I cannot seem to get the body data shown. 使用节点9并表示4。我似乎无法获得所示的主体数据。 After checking other questions, most seem to be resolved using bodyParser.urlencoded , but that doesn't seem to help me. 在检查了其他问题之后,大多数似乎可以使用bodyParser.urlencoded解决,但这似乎无济于事。 What am I doing wrong? 我究竟做错了什么?

server.js 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. call in react看起来像这样,现在我只是想获取补丁以显示数据。 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. get调用有效,console.log“ patch is working”表明也正在调用fetch,但是主体上没有数据。

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 . 仅当请求的Content-Type与您正在使用的解析器匹配时, bodyParser.json()才会解析主体,在本例中为application/json
Your request to your PATCH endpoint needs to include the Content-Type in the request. 您对PATCH端点的请求需要在请求中包括Content-Type

To make request to be treated as JSON from react do so. 为了使react中的请求被视为JSON。

 fetch('/animals', {
   method: 'PATCH', // POST
   headers: {'Content-Type':'application/json'},
   body: {
    "first_name": 'kitten'
   } })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM