简体   繁体   English

如何在Multipart superagent请求中发送对象以及附加文件?

[英]How do I send an Object along with an attached File in a Multipart superagent request?

I am trying to make a multipart POST request to my API using superagent. 我正在尝试使用superagent向我的API发出多部分POST请求。

My Code: 我的代码:

superagent
  .post(apiUrl + '/api/company/profile/edit')
  .field("profileData", profileData)
  .attach('company_logo', logoFile )
  .set('Accept', 'application/json')
  .end(function(err, res){
    if(err){
      dispatch(updateProfileStatusAction("error", res));
    } else {
      dispatch(updateProfileStatusAction("success", res));
    }
  });

The problem I am having is that profileData is an object that is nested. 我遇到的问题是profileData是一个嵌套的对象。 When I get the request in the API I see the value of profileData as the string [Object, Object] 当我在API中获取请求时,我将profileData的值视为字符串[Object, Object]

When I look at the documentation for multipart request with superagent https://visionmedia.github.io/superagent/#multipart-requests it appears like the .field() is meant to be just a key, value pair rather then an object. 当我使用superagent https://visionmedia.github.io/superagent/#multipart-requests查看多部分请求的文档时,看起来.field()只是一个键值对而不是一个对象。 I then tried to use .send({profileData: profileData}) instead of field, but when I do that I get an error saying that .attach and .send can not be used together in the same request. 然后我尝试使用.send({profileData:profileData})而不是字段,但是当我这样做时,我得到一个错误,说.attach和.send不能在同一个请求中一起使用。

I think it should be enough to use JSON.stringify() to convert the JS_Object to a JSON string. 我认为使用JSON.stringify()将JS_Object转换为JSON字符串应该足够了。

superagent
 .post(apiUrl + '/api/company/profile/edit')
 .field("profileData", JSON.stringify(profileData))
 .attach('company_logo', logoFile )
 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM