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

Trying to post multipart/form-data with node.js supertest

本文关键字:发布 multipart form-data supertest js node      更新时间:2023-09-26

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

curl -X POST -F api_key=KEY -F image=@my_file http://localhost:3000/v1/upload

我试了以下,但我得到了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();
});

我也试过这样发送:

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();
});

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

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