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!
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With