尝试使用node.js supertest发布multipart/form-data

San*_*ria 10 javascript node.js superagent supertest

我试图使用Node.js supertest来测试我编写的一些REST API.我需要发送一个等同于以下CURL请求的请求:

curl -X POST -F api_key=KEY -F image=@my_file http://localhost:3000/v1/upload
Run Code Online (Sandbox Code Playgroud)

我尝试了以下,但我得到了Uncaught TypeError: first argument must be a string or Buffer.

request.post('/v1/upload')
.type('form')
.field('api_key', 'abcd')
.attach('image', 'some path')
.end(function(err, res) {
  res.body.error.should.equal('Invalid username/api_key.');
  done();
});
Run Code Online (Sandbox Code Playgroud)

我也试过发送它:

request.post('/v1/upload')
.type('form')
.field('api_key', 'abcd')
.attach('image', 'some path')
.end(function(err, res) {
  res.body.error.should.equal('Invalid username/api_key.');
  done();
});
Run Code Online (Sandbox Code Playgroud)

但服务器只能解析文件上传请求而不是api_key.

小智 10

尝试从测试中删除 .type('form'),因为它将设置application/x-www-form-urlencoded为Content-Type,而不是multipart/form-data.