如何在Multipart superagent请求中发送对象以及附加文件? [英] How do I send an Object along with an attached File in a Multipart superagent request?
问题描述
我正在尝试使用superagent向我的API发出多部分POST请求。
I am trying to make a multipart POST request to my API using superagent.
我的代码:
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));
}
});
我遇到的问题是 profileData
是嵌套的对象。当我在API中收到请求时,我看到 profileData
的值为字符串 [Object,Object]
The problem I am having is that profileData
is an object that is nested. When I get the request in the API I see the value of profileData
as the string [Object, Object]
当我查看带有superagent的多部分请求的文档 .field()只是键,值对而不是对象。然后我尝试使用.send({profileData:profileData})而不是字段,但是当我这样做时,我得到一个错误,说.attach和.send不能在同一个请求中一起使用。
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. 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.
推荐答案
我认为使用 JSON.stringify()
将JS_Object转换为一个JSON字符串。
I think it should be enough to use JSON.stringify()
to convert the JS_Object to a JSON string.
superagent
.post(apiUrl + '/api/company/profile/edit')
.field("profileData", JSON.stringify(profileData))
.attach('company_logo', logoFile )
...
这篇关于如何在Multipart superagent请求中发送对象以及附加文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!