简体   繁体   中英

Restify GET request body

I am building a rest api using restify and I need to allow post body in get requests. I am using bodyparser but it gives only a string. I want it to be an object like in the normal post endpoints.

How can I turn it in to an object? Here is my code:

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

The bodyParser in restify doesn't default to parsing valid JSON (which I assume you are using) for the body of requests that are using the GET method. You have to supply a configuration object to the initialization of bodyParser with the requestBodyOnGet key set to true:

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

To ensure that the body of the request will be JSON, I would also recommend you to check the content-type in your endpoint handler; eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM