如何使用express
检索body
内容呢?
我尝试了body-parser
,但似乎不能与GET
一起使用。有没有其他模块可以实现呢?
var express = require('express'),
bodyParser = require('body-parser'),
PORT = process.env.PORT || 4101,
app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.route('/')
.get(function(req, res) {
respond(req, res, 'GET body contents:\n');
})
.post(function(req, res) {
respond(req, res, 'POST body contents:\n');
});
app.listen(PORT, function(err) {
if (err) {
console.log('err on startup ' + err);
return;
}
console.log('Server listening on port ' + PORT);
});
/*
* Send a response back to client
*/
function respond(req, res, msg){
res.setHeader('Content-Type', 'text/plain');
res.write(msg);
res.end(JSON.stringify(req.body, null, 2));
}
这是
GET
请求的响应内容:GET body contents:
{}
并且从 POST
中:
POST body contents:
{
"gggg": ""
}