version 2
version 2

Reputation: 1059

nodejs- unable to fetch form data

I'm using Express JS (v 4.15.3) for building a node api.

I'm trying to fetch the values send from a form (via POSTman client). I'm not able to fetch it.

This is my form

with headers specified

enter image description here

Without headers

enter image description here

This is how I'm trying to fetch it:

router.post('/login',function(req, res, next) {
    var email= req.body.email;
    //var email= req.query.email; //also tried this
    res.json({
      value: email
    });
});

I'm not getting error.

Note: I have included body parser.

var bodyParser = require('body-parser'); 
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

Can anyone tell me why I am not getting the value? Thanks! This is my first attempt at learning Node JS.

Upvotes: 0

Views: 1294

Answers (2)

Abhay Kumar
Abhay Kumar

Reputation: 550

Your code seems perfectly alright. Though the issue is with the way you are sending request from POSTman client.

When you are sending request using use form data, POSTman sends this request as multipart/form-data, which actually sends your data in the format as below:

POST /api/login HTTP/1.1
Host: localhost:3000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="email"

[email protected]
----WebKitFormBoundaryE19zNvXGzXaLvS5C

For multipart/form-data requests you need to use multer middleware, if you really need file-uploads with your application. But for your case you can just send data without using use form data (un-check the use form data checkbox), and setting content-type header as:

Content-Type: application/x-www-form-urlencoded

So after all these modifications your raw web request should look something like below:

POST /api/login HTTP/1.1
Host: localhost:3000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache

[email protected]

The POSTman screen capture for building the request and response is as below:

POSTman screen capture for building the request and response

The POSTman screen capture for Raw request and response is as below:

POSTman screen capture for Raw request and response

Hope this will help you.

Upvotes: 1

sohamdodia
sohamdodia

Reputation: 377

Try to set Content-Type to application/json and in body in raw write in json format like this :

{
    "email":"[email protected]"
}

Here are the images which you can refer.

enter image description here

enter image description here

Don't forget to upvote the answer if you find it helpful.

Upvotes: 0

Related Questions