通过Chai发布请求

时间:2016-02-29 10:54:59

标签: node.js mocha chai


我正在尝试向我的节点JS服务器发出请求,该服务器接受post / put调用。我试图通过chai通过邮件调用发送的参数在服务器上不可见(req.body.myparam)。
我已尝试过以下帖子请求,但最终没有结果: -

var host = "http://localhost:3000";
var path = "/myPath";
 chai.request(host).post(path).field('myparam' , 'test').end(function(error, response, body) {

chai.request(host).post(path).send({'myparam' : 'test'}).end(function(error, response, body) {

节点JS代码如下: -

app.put ('/mypath', function(req, res){                     //Handling post request to create league
    createDoc (req, res);
})


app.post ('/mypath', function(req, res){                        //Handling post request to create league
    createDoc (req, res);
})

var createDoc = function (req, res) {
    var myparam = req.body.myparam;                                 //league id to create new league
    if (!myparam) {
        res.status(400).json({error : 'myparam is missing'});
        return;
    }       
};

以上代码遗失给myparam。

请让我知道做同样事情的最佳方法是什么 在此先感谢。

2 个答案:

答案 0 :(得分:23)

您编写的方式,我假设您使用了 chai-http 包。 .field()函数在 chai-http 中不起作用。另一位用户指出here并在github上打开了一个问题。

以下是您的写作方式:

.set('content-type', 'application/x-www-form-urlencoded')
.send({myparam: 'test'})

以下是成功将参数传递给服务器的完整代码:

<强> test.js

'use strict';
var chai = require('chai');
var chaiHttp = require('chai-http');

chai.use(chaiHttp);

describe('Test group', function() {
    var host = "http://" + process.env.IP + ':' + process.env.PORT;
    var path = "/myPath";

    it('should send parameters to : /path POST', function(done) {
        chai
            .request(host)
            .post(path)
            // .field('myparam' , 'test')
            .set('content-type', 'application/x-www-form-urlencoded')
            .send({myparam: 'test'})
            .end(function(error, response, body) {
                if (error) {
                    done(error);
                } else {
                    done();
                }
            });
    });
});

<强> server.js

'use strict';
var bodyParser  = require("body-parser"),
    express     = require("express"),
    app         = express();

app.use(bodyParser.urlencoded({extended: true}));

app.put ('/mypath', function(req, res){  //Handling post request to create league
    createDoc (req, res);
});

app.post ('/mypath', function(req, res){  //Handling post request to create league
    createDoc (req, res);
});

var createDoc = function (req, res) {
    console.log(req.body);
    var myparam = req.body.myparam; //league id to create new league
    if (!myparam) {
        res.status(400).json({error : 'myparam is missing'});
        return;
    }
};

app.listen(process.env.PORT, process.env.IP, function(){
    console.log("SERVER IS RUNNING");
});

module.exports = app;

答案 1 :(得分:8)

我找到了两种用空req.body解决问题的方法。

  1. body作为表单数据

    .put('/path/endpoint')
    .type('form')
    .send({foo: 'bar'})
    // .field('foo' , 'bar')
    .end(function(err, res) {}
    
    // headers received, set by the plugin apparently
    'accept-encoding': 'gzip, deflate',
    'user-agent': 'node-superagent/2.3.0',
    'content-type': 'application/x-www-form-urlencoded',
    'content-length': '127',
    
  2. bodyapplication/json

    .put('/path/endpoint')
    .set('content-type', 'application/json')
    .send({foo: 'bar'})
    // .field('foo' , 'bar')
    .end(function(err, res) {}
    
    // headers received, set by the plugin apparently
    'accept-encoding': 'gzip, deflate',
    'user-agent': 'node-superagent/2.3.0',
    'content-type': 'application/json',
    'content-length': '105',
    
  3. 在这两种情况下,我都使用.send({foo: 'bar'})而非.field('foo' , 'bar')

    这个问题显然与chai-http无关。这是superagent的问题。 chai-http正在使用superagent

    superagent尝试玩机器学习并为我们猜测。这是他们的docs say

      

    默认情况下,发送字符串会将Content-Type设置为application/x-www-form-urlencoded

         

    SuperAgent格式是可扩展的,但默认情况下支持“json”和“form”。要将数据作为application/x-www-form-urlencoded发送,只需使用“表单”调用.type(),其中默认值为“json”。

      request.post('/user')
        .type('form')
        .send({ name: 'tj' })
        .send({ pet: 'tobi' })
        .end(callback)
    

    chai-http最大的错误是他们没有正确记录他们的插件。您必须在互联网上搜索答案,而不是在chai-http GitHub页面上搜索答案。