重新整理GET请求主体

编码器

我正在使用restify构建rest api,我需要在get请求中允许发布正文。我正在使用bodyparser,但它只提供一个字符串。我希望它是一个像普通发布端点中那样的对象。

如何将它变成一个对象?这是我的代码:

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);
});
毫米波

restify中的bodyParser不会默认为使用GET方法的请求正文解析有效的JSON(我假设您正在使用)您必须将requestBodyOnGet键设置为true的bodyParser初始化提供一个配置对象

server.use(restify.bodyParser({
    requestBodyOnGet: true
}));

为了确保请求的主体为JSON,我还建议您检查端点处理程序中content-type例如:

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);
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章