This is the code of my server :
var express = require('express'); var bodyParser = require("body-parser"); var app = express(); app.use(bodyParser.json()); app.post("/", function(req, res) { res.send(req.body); }); app.listen(3000, function () { console.log('Example app listening on port 3000!'); });
From Postman, I launch a POST request to http://localhost:3000/ and in Body/form-data I have a key "foo" and value "bar".
However I keep getting an empty object in the response. The req.body
property is always empty.
Did I miss something?
js POST Method. Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.
POST request (web browser) var http = new XMLHttpRequest(); var params = "text=stuff"; http. open("POST", "http://someurl.net:8080", true); http. setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.
Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.
Add the encoding of the request. Here is an example
.. app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); ..
Then select x-www-form-urlencoded
in Postman or set Content-Type to application/json
and select raw
Edit for use of raw
Raw
{ "foo": "bar" }
Headers
Content-Type: application/json
EDIT #2 Answering questions from chat:
You sure can, just look at this answer How to handle FormData from express 4
x-www-form-urlencoded
and raw
differences in application/json and application/x-www-form-urlencoded
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