【发布时间】:2018-12-25 20:46:54
【问题描述】:
我正在尝试从我的节点服务器向api that expects a file and other form data as an multipart/form-data 发送一个发布请求。
这是我的代码的样子
var importResponse = function(csv){
stringify(csv, function(err, output){
request.post({
headers: {'X-API-TOKEN':token, 'content-type' : 'multipart/form-data'},
url: url,
formData: {
surveyId: surveyId,
file: {
value: output,
options: {
fileName: 'test.csv',
contentType:'text/csv'
}
}
}
}, function(error, response, body){
console.log(body);
});
});
}
使用request-debug 是请求:
request:
{ debugId: 1,
uri: 'https://co1.qualtrics.com/API/v3/responseimports',
method: 'POST',
headers:
{ 'X-API-TOKEN': 'removed',
'content-type':
'multipart/form-data; boundary=--------------------------010815605562947295265820',
host: 'co1.qualtrics.com',
'content-length': 575 } } }
以及回应:
response:
{ debugId: 1,
headers:
{ 'content-type': 'application/json',
'content-length': '188',
'x-edgeconnect-midmile-rtt': '28',
'x-edgeconnect-origin-mex-latency': '56',
date: 'Wed, 18 Jul 2018 03:57:59 GMT',
connection: 'close',
'set-cookie': [Array],
'strict-transport-security': 'max-age=31536000; includeSubDomains; preload' },
statusCode: 400,
body:
'{"meta":{"httpStatus":"400 - Bad Request","error":{"errorMessage":"Missing Content-Type for file part. name=file","errorCode":"MFDP_3"},"requestId":"322a16db-97f4-49e5-bf10-2ecd7665972e"}}' } }
我得到的错误是:Missing Content-Type for file part.
我在选项中添加了这个:
options: {
fileName: 'test.csv',
contentType:'text/csv'
}
当我查看请求时,似乎没有包含表单数据。但也许这只是request-debug 没有显示它。
我看到了类似的SO question,答案是使用JSON.stringify。
我尝试将代码更改为以下内容:
request.post({
headers: {'X-API-TOKEN':token, 'content-type' : 'multipart/form-data'},
url: url,
body: JSON.stringify({
surveyId: surveyId,
file: {
value: output,
options: {
fileName: 'test.csv',
contentType:'text/csv'
}
}
})
但是,我收到以下错误:
{"meta":{"httpStatus":"400 - Bad Request","error":{"errorMessage":"Missing boundary header"}}}
我做错了什么?
更新
当我尝试将文件值更改为计算机上的 csv fs.createReadStream('test.csv') 时,它运行良好
file: {
value: fs.createReadStream('test.csv'),
options: {
contentType: 'text/csv'
}
}
所以我认为我提供文件的方式有问题。我用作文件的output 变量看起来就像"QID1,QID2\nQID1,QID2\n1,2"。我认为这是导致问题的原因,即使该错误有点误导。我尝试创建一个Readable,我发现它是一个StackOverFlow answer,如下所示:
var s = new Readable
s.push(output)
s.push(null)
但是,这会导致Unexpected end of input
{"meta":{"httpStatus":"400 - Bad Request","error":{"errorMessage":"Unexpected end of input"}}}
【问题讨论】:
标签: javascript node.js