Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How do I get the post request with express js?

How do I get the post request with express js?

Problem

I'm trying to get the post variables in a little service I wrote but cannot seem to get it out of the Request variable in my app.post method. I believe it's some way that I'm processing the request. Are there additional steps I must take to process the request? I've also tried using Express.bodyParser() but I got an error saying that this is deprecated. The following is my little node.js file:

        var express = require('express');
        var app = express();
        app.use(express.json());
        // posting method : curl -X POST http://localhost:8080/post-page -d name=ArrowKneeous
        // to look at the req I found it better to start using: 
        // nohup node testPost.js > output.log &
        app.post('/post-page',function(req,res){
        var name= req.body.name;
        //undefined
        console.log('name is :' + name);
        //object
         console.log('req is: '+req);
        //object
        console.log('req.body is: ' +req.body);
        //undefined
        console.log('req.body.name is: '+req.body.name);
        //undefined
         console.log('req.params[0]: '+req.params[0]);
         //undefined
         console.log('req.query.name is: '+req.query.name);
         //empty brackets
         console.dir(req.body);
         //huge
         console.dir(req);
         //got stuff is replied to the curl command
         res.send('got stuff');
       });
    app.listen(8080);
Problem courtesy of: ArrowKneeous

Solution

You have

app.use(express.json());

to process a JSON post, but are POSTing standard URL encoded form data.

-d name=ArrowKneeous

You either need to post JSON

-d '{"name": "ArrowKneeous"}' -H "Content-Type: application/json"

or you need to tell express to also accept URL encoded POST data.

app.use(express.urlencoded());

Edit

This applies to Express 3.x. It should be almost the same with 4.x, but you will need to load the body-parser module instead:

var bodyParser = require('body-parser');

app.use(bodyParser.json());
// OR
app.use(bodyParser.urlencoded());
Solution courtesy of: loganfsmyth

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How do I get the post request with express js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×