简体   繁体   English

req.body.data 在 nodejs 中未定义

[英]req.body.data got undefined in nodejs

My client side我的客户端

$.post("http://localhost:3000/scrape",
      {
      data: 'something'
      },
      function(data, status){
      console.log(data);
      });

What I do in node.js我在 node.js 中做什么

var express = require('express');

var app = express();

var bodyParser = require('body-parser');

app.use(bodyParser.json());

app.post('/scrape', function (req, res) {

    console.log(req.body.data)

});

But I got undefined in console.log(req.body.data), any idea why?但是我在 console.log(req.body.data) 中没有定义,知道为什么吗?

Your data must be of json format.您的数据必须是 json 格式。 since you are using bodyParser.json() .因为您使用的是bodyParser.json()

Try setting the http header, Content-type as application/json in your $.post call and send a valid json structure as data尝试在$.post调用中将 http 标头、 Content-typeapplication/json并发送有效的 json 结构作为数据

  $.ajax({
    url: "scrape", 
    type: "POST",
    data: JSON.stringify({ someData : "someData}),
    contentType:"application/json; charset=utf-8",
    dataType:"json",
    success: function(data){
          console.log(data)
    },
    error: function(){
          console.log('error in sending request')
    }
})
console.log(req.body.data)

returns undefined because the data is in req.body you should console.log(req.body) and add app.use(bodyParser.urlencoded({extended: false}));返回 undefined 因为数据在req.body你应该console.log(req.body)并添加app.use(bodyParser.urlencoded({extended: false})); so that data not in json format can also be parsed.这样也可以解析非json格式的数据。

if you want req.body.data have data then make request like如果你想要req.body.data有数据,那么提出请求

$.post("http://localhost:3000/scrape",
      {
      data: {data: 'something'}
      },
      function(data, status){
      console.log(data);
      });

also your request is not sending any response you need to do something like您的请求也没有发送您需要做的任何响应

app.post('/scrape', function (req, res) {

    console.log(req.body.data)
    res.status(200).json({data: reqr.body.data});

});

hope it helps :)希望能帮助到你 :)

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

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