【问题标题】:Post request via Chai通过 Chai 发布请求
【发布时间】:2016-06-12 09:16:39
【问题描述】:


我正在尝试向接受 post/put 调用的节点 JS 服务器发出请求。我试图通过 chai 通过 post 调用发送的参数在服务器 (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) {

Node 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 丢失了。

请告诉我最好的方法是什么。
提前致谢。

【问题讨论】:

  • 可以分享端点的代码吗?
  • 更新了代码。如果您还需要什么,请告诉我。
  • 我没有看到 league 在任何地方定义?
  • 我的错误。没有正确复制代码。更新了上面的代码。请检查。谢谢

标签: node.js mocha.js chai


【解决方案1】:

按照你写的方式,我假设你使用了 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;

【讨论】:

  • 这对我有用。这很有趣,因为文档说在发布表单数据时使用 .field() 方法,但如果您在服务器上以这种方式使用 bodyParser 可能不起作用?
  • 如何在此附加文件?我知道这是代码 .attach('imageField', fs.readFileSync('avatar.png'), 'avatar.png') 但不确定在哪里附加它
  • 如果您在测试中不需要 module.exports = app;,您会做什么?如果你导出它,你可以要求它,然后chai.request(server).post(path)。这将让您 mockspy,例如使用npmjs.com/package/sinon-chai
  • 8 小时的研究,终于.set('content-type', 'application/x-www-form-urlencoded') 解决了一切!!!谢谢你一百万次@C00bra。这应该是标记的答案!
【解决方案2】:

我找到了两种解决空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',
    

在这两种情况下,我都使用.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 发送,只需使用“form”调用.type(),默认为“json”。

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

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

【讨论】:

  • 如何在此附加文件?我知道这是代码 .attach('imageField', fs.readFileSync('avatar.png'), 'avatar.png') 但不确定在哪里附加它
猜你喜欢
  • 1970-01-01
  • 2016-06-04
  • 2019-01-12
  • 2017-11-21
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
相关资源
最近更新 更多