通过Chai发布请求

SCJ*_*PWR 19 mocha.js node.js chai


我正在尝试向我的节点JS服务器发出请求,该服务器接受post/put调用.我试图通过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) {
Run Code Online (Sandbox Code Playgroud)

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

节点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;
    }       
};
Run Code Online (Sandbox Code Playgroud)

以上代码转到myparam缺失.

请让我知道最好的方法是什么.
提前致谢.

小智 25

你写的方式,我假设你使用chai-http包.该点域()函数不工作柴HTTP.另一位用户在这里指出并在github上打开了一个问题.

以下是你可以写的:

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

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

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();
                }
            });
    });
});
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)


Gre*_*een 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',
    
    Run Code Online (Sandbox Code Playgroud)
  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',
    
    Run Code Online (Sandbox Code Playgroud)

在这两种情况下我都使用.send({foo: 'bar'})而不是.field('foo' , 'bar').

这个问题显然与此无关chai-http.这是个superagent问题.并在引擎盖下chai-http使用superagent.

superagent尝试玩机器学习并为我们猜测.以下是他们的文档所说的内容:

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

SuperAgent格式是可扩展的,但默认情况下支持"json"和"form".发送数据application/x-www-form-urlencoded只需.type()使用"form" 调用,默认为"json".

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

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