Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get POST data using NodeJS/ExpressJS and Postman

Tags:

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?enter image description here

like image 326
user2923322 Avatar asked Jan 31 '17 10:01

user2923322


People also ask

What is POST () in Express?

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.

How do I accept a post request in node?

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.

How do you send a POST request in node JS?

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.


1 Answers

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:

  1. why it can't work with form-data?

You sure can, just look at this answer How to handle FormData from express 4

  1. What is the difference between using x-www-form-urlencoded and raw

differences in application/json and application/x-www-form-urlencoded

like image 183
R. Gulbrandsen Avatar answered Oct 12 '22 23:10

R. Gulbrandsen