简体   繁体   中英

Getting POST parameters in Node.js, using Express.js

I'm trying to get some POST parameters following a request using Express, but I cannot get the data. Here's my app.configure :

app.configure(function() {
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');

    app.use(express.bodyParser());
    app.use(express.methodOverride());

    app.use(gzippo.staticGzip(__dirname + '/public'));
    app.use(gzippo.compress());
});

After a POST HTTP request, I try to ouptut it in the console:

console.log(req.body);

The object is always empty.

Any idea on what I forgot?

You have to use req.body to retrieve body parameters. You must use a form in your HTML code too.

Example:

<form action="myaction" method="post">
  <input name="address" id="address" type="text" />
  <button type="submit" value="Send" />
</form>

...

In your form:

var address = req.body.address; //get address value

The only thing I needed to do it, was to add the body parser and app.post lines from this code:

app.use(express.static(__dirname + '/public'))
    .use(express.favicon())
    .use(express.bodyParser())
    .use(express.cookieParser(COOKIE_P))
    .use(express.session());

app.post('/',function(req,res){
    res.writeHead(200,{"content-type":"text/html;charset=UTF8;"});
    res.end("POST");
    console.log(req.body);
});

My fail was try to get the values from app.get instead of app.post.

Try to swap the following lines:

app.use(express.bodyParser());
app.use(express.methodOverride());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM