我正在使用restify构建rest,我需要在get请求中允许post主体。我正在使用only解析器,但它只给出了一个字符串。我希望它是一个对象,像在正常的post端点。
我怎样才能把它交给一个物体呢?这是我的代码:
const server = restify.createServer();
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.get('/endpoint', function (req, res, next) {
console.log(typeof req.body);
console.log(req.body && req.body.asd);
res.send(200);
});发布于 2017-06-15 19:01:55
restify中的bodyParser不默认为使用GET方法的请求体解析有效的JSON (我假设您正在使用该JSON)。您必须为bodyParser的初始化提供一个配置对象,并将requestBodyOnGet键设置为true:
server.use(restify.bodyParser({
requestBodyOnGet: true
}));为了确保请求的主体是JSON,我还建议您检查端点处理程序中的内容类型;例如:
const server = restify.createServer();
server.use(restify.queryParser());
server.use(restify.bodyParser({
requestBodyOnGet: true
}));
server.get('/endpoint', function (req, res, next) {
// Ensures that the body of the request is of content-type JSON.
if (!req.is('json')) {
return next(new restify.errors.UnsupportedMediaTypeError('content-type: application/json required'));
}
console.log(typeof req.body);
console.log(req.body && req.body.asd);
res.send(200);
});https://stackoverflow.com/questions/44574906
复制相似问题