使用Node.js,GET,正文解析器从GET请求中解析正文? [英] Parse body from GET request using nodejs, express, body-parser?
本文介绍了使用Node.js,GET,正文解析器从GET请求中解析正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用express
检索body
内容?
Is it possible to retrieve the body
contents using express
?
我从尝试body-parser
开始,但似乎不适用于GET
.有没有可行的模块?
I started by trying body-parser
but that doesn't seem to work with GET
. Are there any modules which would work?
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": ""
}
推荐答案
GET请求没有正文,它们具有查询字符串.为了访问expressJS中的查询字符串,您应该使用req.query
对象.
GET requests don't have a body, they have query strings. In order to access a query string in expressJS you should use the req.query
object.
res.end(JSON.stringify(req.query, null, 2));
这篇关于使用Node.js,GET,正文解析器从GET请求中解析正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文