最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node js Request body type is [Object, Object] - Stack Overflow

programmeradmin1浏览0评论

I want to send a request with a custom string value to the server with express and body-parser in Node.js, but I get the following when I try to inspect the posted value.

[object Object]

Server -

var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.post('/', callback)

function callback(req, res) {
  console.log('post/' + req.body)
  res.send('post success!')
}

Client -

var request = require('request')
request.post({
  url: 'http://127.0.0.1:8000/',
  body: 'testing'
}, function optionalCallback (err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err)
  }
  console.log('Upload successful!  Server responded with:', body)
})

Client logs -

Upload successful! Server responded with: post success!

Server logs -

post/[object Object]

how can I get the string content "testing" instead? Thank you!

I want to send a request with a custom string value to the server with express and body-parser in Node.js, but I get the following when I try to inspect the posted value.

[object Object]

Server -

var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.post('/', callback)

function callback(req, res) {
  console.log('post/' + req.body)
  res.send('post success!')
}

Client -

var request = require('request')
request.post({
  url: 'http://127.0.0.1:8000/',
  body: 'testing'
}, function optionalCallback (err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err)
  }
  console.log('Upload successful!  Server responded with:', body)
})

Client logs -

Upload successful! Server responded with: post success!

Server logs -

post/[object Object]

how can I get the string content "testing" instead? Thank you!

Share Improve this question edited Jun 22, 2017 at 20:40 scniro 17k8 gold badges66 silver badges107 bronze badges asked Jun 22, 2017 at 18:57 DeidaraDeidara 6772 gold badges14 silver badges28 bronze badges 2
  • remove the toString() off from req.body. – gforce301 Commented Jun 22, 2017 at 19:17
  • 3 tried using JSON.stringify on it, or console.dir instead of .log? – m_callens Commented Jun 22, 2017 at 20:42
Add a comment  | 

5 Answers 5

Reset to default 4

Looks like you need to post via form data - which through request[forms] - will apply the appropriate application/x-www-form-urlencoded http header. Observe the following...

// -- notice the keyed object being sent
request.post('http://127.0.0.1:8000/', {
  form: {customKey: 'testing'}
}, function (err, httpResponse, body) {

  console.log(body); // post success!
});

On your endpoint, if you want to log this out you can then do so as such...

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

  console.log('post/ ', req.body.customKey'); // -- post/ testing
  res.send('post success!');
});

If you want to see [object Object] content in console.log try this:

const util = require('util');
...
console.log(`post/${util.inspect(req.body,false,null)}`);

More info: util.inspect

The easy way to do this is with console.dir() instead of console.log().

The Console method dir() displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.

In other words, console.dir() is the way to see all the properties of a specified JavaScript object in console by which the developer can easily get the properties of the object.

I was using a validation middleware.. and hence this was an issue. the validator was ..

BookingBodyValidation: [
    sanitizeBody("*")
      .trim()
      .escape(),
    body("refNo").notEmpty()
  ]

removing this "sanitizeBody().trim().escape()" solved the issue.

Someone might find this handy... for the server-side, I wrote a little JS snippet that parses out the key/value pairs of an incoming req.body (application/x-www-form-urlencoded) and displays them on the console as a valid JSON object:

const util=require('util');let s=util.inspect(req.body)
.split(`Content-Disposition: form-data; name`);s.splice(0,1);
let r=`{"`;s.forEach((e)=>{r+=e.split(`\\r\\n------`)[0]
.replace(`"\\r\\n\\r\\n`,`":"`).replace(`\': \'"`,``)
.replace(`=`,``)+`",`});s=r.slice(0,-1)+`}`;console.log(s);
发布评论

评论列表(0)

  1. 暂无评论