首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Restify获取请求体

Restify获取请求体
EN

Stack Overflow用户
提问于 2017-06-15 18:53:21
回答 1查看 3.9K关注 0票数 3

我正在使用restify构建rest,我需要在get请求中允许post主体。我正在使用only解析器,但它只给出了一个字符串。我希望它是一个对象,像在正常的post端点。

我怎样才能把它交给一个物体呢?这是我的代码:

代码语言:javascript
复制
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);
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-15 19:01:55

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

代码语言:javascript
复制
server.use(restify.bodyParser({
    requestBodyOnGet: true
}));

为了确保请求的主体是JSON,我还建议您检查端点处理程序中的内容类型;例如:

代码语言:javascript
复制
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);
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44574906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档