使POST参数无法正常工作

问题描述 投票:1回答:2

我正在尝试使用postMan使用restify框架发送post参数(key:test,value:somevlaue)。为此,我使用了2种方法,两种方法都不起作用:

第一个显示此错误:

{
  "code": "InternalError",
  "message": "Cannot read property 'test' of undefined"
}

第二个(评论)仅显示错误:某个错误

难道我做错了什么?

这是我的代码:

var restify=require('restify');
var fs=require('fs');
var qs = require('querystring');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
var controllers = {};

var server=restify.createServer();

server.post("/get", function(req, res, next){
    res.send({value: req.body.test,
     error: "someerror"});

    //**********METHOD TWO*********************

/*
     if (req.method == 'POST') {
         var body = '';

         req.on('data', function (data) {
             body += data;
         });

         req.on('end', function () {
             var post = qs.parse(body);
             res.send({
                 Data: post.test,
                 Error: "Someerror"
             });
         });
     }
     */

});
server.listen(8081, function (err) {
    if (err)
        console.error(err);
    else
        console.log('App is ready at : ' + 8081);
});
javascript node.js express restify
2个回答
0
投票

看起来您可能错误地设置了bodyparser。根据body解析器部分下的the docs,您可以通过以下方式设置解析器:

server.use(restify.bodyParser({
    maxBodySize: 0,
    mapParams: true,
    mapFiles: false,
    .....
 }));

默认是将数据映射到req.params,但您可以通过将req.body选项设置为mapParams来更改此值并将其映射到false

BodyParser

在读取和解析HTTP请求主体时阻止您的链。切换Content-Type并执行适当的逻辑。目前支持application / json,application / x-www-form-urlencoded和multipart / form-data。


0
投票

通过restify ^ 7.7.0,您不必再需要('body-parser')。只需使用restify.plugins.bodyParser():

var server = restify.createServer()
server.listen(port, () => console.log(`${server.name} listening ${server.url}`))
server.use(restify.plugins.bodyParser()) // can parse Content-type: 'application/x-www-form-urlencoded'
server.post('/your_url', your_handler_func)
© www.soinside.com 2019 - 2024. All rights reserved.