恢复 GET 请求正文
Restify GET request body
我正在使用 restify 构建一个 rest api,我需要在 get 请求中允许 post body。我正在使用 bodyparser 但它只提供一个字符串。我希望它成为一个对象,就像在正常 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);
});
restify 中的 bodyParser 不会默认为使用 GET 方法的请求正文解析有效的 JSON(我假设您正在使用) .您必须为 bodyParser 的初始化提供一个配置对象,并将 requestBodyOnGet 键设置为 true:
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);
});
我正在使用 restify 构建一个 rest api,我需要在 get 请求中允许 post body。我正在使用 bodyparser 但它只提供一个字符串。我希望它成为一个对象,就像在正常 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);
});
restify 中的 bodyParser 不会默认为使用 GET 方法的请求正文解析有效的 JSON(我假设您正在使用) .您必须为 bodyParser 的初始化提供一个配置对象,并将 requestBodyOnGet 键设置为 true:
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);
});