如何使用 Chai Http post 对象数组

How to post an array of objects with Chai Http

我正在尝试 post 具有 ChaiHttp 的对象数组,如下所示:

agent.post('route/to/api')
  .send( locations: [{lat: lat1, lon: lon1}, {lat: lat2, lon: lon2}])
  .end (err, res) -> console.log err, res

returns 错误如下:

 TypeError: first argument must be a string or Buffer
at ClientRequest.OutgoingMessage.end (_http_outgoing.js:524:11)
at Test.Request.end (node_modules/superagent/lib/node/index.js:1020:9)
at node_modules/chai-http/lib/request.js:251:12
at Test.then (node_modules/chai-http/lib/request.js:250:21)

events.js:141 throw er; // Unhandled 'error' event ^

Error: incorrect header check at Zlib._handle.onerror (zlib.js:363:17)

我也试过 post 像这样,就像我们对 postman:

agent.post('route/to/api')
  .field( 'locations[0].lat', xxx)
  .field( 'locations[0].lan', xxx)
  .field( 'locations[1].lat', xxx)
  .field( 'locations[2].lat', xxx)
  .then (res) -> console.log res

但 payload.locations 收到时未定义。

知道如何通过 chai-http post 对象数组吗?

编辑:

这是我的路线,我认为流负载有问题:

method: 'POST'
path:
config:
  handler: my_handler
  payload:
    output: 'stream'

我在这里遇到了同样的问题。似乎只是 chai-http 文档是错误的。它说:

// Send some Form Data
chai.request(app)
 .post('/user/me')
 .field('_method', 'put')
 .field('password', '123')
 .field('confirmPassword', '123')

这是行不通的。这对我有用:

chai.request(app)
  .post('/create')
  .send({ 
      title: 'Dummy title',
      description: 'Dummy description'
  })
  .end(function(err, res) { ... }

尝试使用.send({locations: [{lat: lat1, lon: lon1}, {lat: lat2, lon: lon2}]})。因为 .field('a', 'b') 不工作。

  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. body 作为 application/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',
    

面临同样的问题,我的解决方案是不使用 JSON 对象作为发送方法,而是使用原始字符串:

    chai.request(uri)
        .post("/auth")
        .set('content-type', 'application/x-www-form-urlencoded')
        .send(`Login[Username]=${validUser1.username}`)
        .send(`Login[Password]=${validUser1.password}`)
        .send(`RememberMe=false`)
        .end((err, res) => {
            res.should.have.status(200);
            // ...
        });