如何使用 node.js superagent 发布 multipart/form-data

2024-03-08

我正在尝试将超级代理发布请求中的内容类型发送到 multipart/form-data。

var myagent = superagent.agent();

myagent
  .post('http://localhost/endpoint')
  .set('api_key', apikey)
  .set('Content-Type', 'multipart/form-data')
  .send(fields)
  .end(function(error, response){
    if(error) { 
       console.log("Error: " + error);
    }
  });

我得到的错误是: 类型错误:参数必须是字符串

如果我删除:

.set('Content-Type', 'multipart/form-data')

我没有收到任何错误,但我的后端正在接收内容类型为:application/json 的请求

如何强制内容类型为 multipart/form-data 以便我可以访问 req.files()?


首先,您没有提及以下任何一项:

.set('Content-Type', 'multipart/form-data')

OR

.type('form')

其次,你不使用.send, 你用.field(name, value).

Examples

假设您想发送包含以下内容的表单数据请求:

  • 两个文本字段:name and phone
  • 一个文件:photo

所以你的请求将是这样的:

superagent
  .post( 'https://example.com/api/foo.bar' )
  .set('Authorization', '...')
  .accept('application/json')
  .field('name', 'My name')
  .field('phone', 'My phone')
  .attach('photo', 'path/to/photo.gif')

  .then((result) => {
    // process the result here
  })
  .catch((err) => {
    throw err;
  });

并且,假设您想要将 JSON 作为其中一个字段的值发送,那么您就可以这样做。

try {
  await superagent
         .post( 'https://example.com/api/dog.crow' )
         .accept('application/json')
         .field('data', JSON.stringify({ name: 'value' }))
}
catch ( ex ) {
    // .catch() stuff
}

// .then() stuff...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 node.js superagent 发布 multipart/form-data 的相关文章

随机推荐