我有两台节点服务器。一个是尝试读取文件,另一个是发送文件。我的服务器设置如
.post(upload.array('test'), function (req, res) {
if (!Array.isArray(req.files)) {
res.status(400).json({success: false, err: 'Must have test(s))'});
return;
}
var files = req.files; <-- This is always null
我的客户端看起来像
var http = require('request-promise');
var request = require('request');
var fs = require('fs');
var FormData = require('form-data');
var form = new FormData();
tests.forEach(function(testName){
form.append('test', fs.createReadStream(__dirname+'/tests/'+testName));
});
var options = {
method: 'POST',
uri: 'https://' + name +'/rest/api',
rejectUnauthorized: false,
timeout: 2000,
form: form,
};
return http(options);
然而,服务器永远无法找到文件。响应总是说错误:必须有测试。
任何人都可以帮助我找出我在客户身上做错的事吗?
答案 0 :(得分:1)
form
选项适用于urlencoded表单。对于多部分表单,您需要设置formData
选项。此外,您不需要明确使用form-data
模块。例如:
var requestPromise = require('request-promise');
var fs = require('fs');
var formTests = new Array(tests.length);
for (var i = 0; i < tests.length; ++i)
formTests[i] = fs.createReadStream(__dirname + '/tests/' + tests[i]);
var options = {
method: 'POST',
uri: 'https://' + name +'/rest/api',
rejectUnauthorized: false,
timeout: 2000,
formData: {
tests: formTests
}
};
return requestPromise(options);