Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js Request body type is [Object, Object]

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!

like image 725
Deidara Avatar asked Jun 22 '17 18:06

Deidara


1 Answers

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!');
});
like image 64
scniro Avatar answered Sep 28 '22 10:09

scniro