Node Request body type js [Object, Object]
I want to send a request with a custom string value to a server with an expression and body-parser in Node.js, but I get the following when I try to validate 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!')
}
Customer -
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)
})
Customer logs -
Upload successfully! The server replied: post success!
Server logs -
post / [object Object]
how can I get the content of the string "testing"
instead? Thank!
source to share
It looks like you need to send via that via [forms] - will apply the appropriate http header . Observe the following ... request
application/x-www-form-urlencoded
// -- 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!
});
At the end point, if you want to record this, you can do it as such ...
app.post('/', function (req, res) {
console.log('post/ ', req.body.customKey'); // -- post/ testing
res.send('post success!');
});
source to share
If you want to see the contents of [object Object] in console.log try this:
const util = require('util');
...
console.log(`post/${util.inspect(req.body,false,null)}`);
More information: util.inspect
source to share
Someone might find this handy ... for the server side, I wrote a small JS snippet that parses the key / value pairs of the 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);
source to share