bob*_*e01 3 node.js express body-parser
是否可以使用 检索body
内容express
?
我开始尝试,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));
}
Run Code Online (Sandbox Code Playgroud)
这是来自GET
:
GET body contents:
{}
Run Code Online (Sandbox Code Playgroud)
来自POST
:
POST body contents:
{
"gggg": ""
}
Run Code Online (Sandbox Code Playgroud)
GET 请求没有正文,它们有查询字符串。为了访问 expressJS 中的查询字符串,您应该使用该req.query
对象。
res.end(JSON.stringify(req.query, null, 2));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8508 次 |
最近记录: |