我正在使用一个API,要求我在表单字段中放置一个数组。给出的示例是在PHP中,但我使用的是NodeJS。 API期望其中一个字段是一个数组,我很难弄清楚如何做到这一点。
PHP示例如下所示:
$scope.strike = function() {
var oldList = $scope.todoList;
angular.forEach(oldList, function(x) {
x.isStriked = x.done;
});
};
在NodeJS中我尝试了这个(除其他外):
$request->buildPostBody(array(
'reference' => array(
'line1' => 'Soundboard Setup',
'line2' => 'Thank you for the order',
'line3' => 'Our reference is: 3993029/11BD'
),
'lines' => array(
array('amount' => 50,
'amount_desc' => 'panels',
'description' => 'Sound buttons',
'tax_rate' => 21,
'price' => 5.952
),
array('amount' => 1,
'amount_desc' => '',
'description' => 'Wooden case',
'tax_rate' => 21,
'price' => 249
),
array('amount' => 10,
'amount_desc' => 'hours',
'description' => 'Support',
'tax_rate' => 6,
'price' => 62.5
),
array('description' => 'This is a textline'))
));
当我尝试传递这样的对象时:var formData = {
reference: [{'line1':'something'}], // <- this isn't going to fly
lines: [{
'amount': amount,
'amount_desc': 'amount_desc',
'description': 'description',
'tax_rate': 0,
'price': 100
}]
};
request.post({
url: 'https://www.factuursturen.nl/api/v1/invoices/',
formData: formData,
headers: {
'Authorization': 'Basic ' + new Buffer(user + ':' + key).toString('base64')
}
}, function (error, response, body) {
if (!error && [200, 201, 204].indexOf(response.statusCode) > 0) {
console.log('posted ': ', response.statusCode);
} else {
console.log('problem with request: ', error, response.statusCode, body);
}
}
);
我从Node收到错误:
reference: {'line1':'foo'}
我怎样才能最好地将这个圆形钉子钉入那个方孔?
答案 0 :(得分:2)
在PHP中,数组可以是数组 和 ,它们可以是关联数组,它们实际上是JavaScript中的对象。
使用array()
进行指定可以使用array()语言构造创建array。它需要任意数量的逗号分隔键=&gt;值对作为参数。
array( key => value, key2 => value2, key3 => value3, ... )
在JavaScript中,上面基本上只是 对象
{
key: 'value',
key2: 'value2'
key3: 'value3'
...
}
它不会是一个包裹在数组[{…}]
内的对象,这就是你对reference
因此,为了模仿PHP结构,您的数据应该是这样的:
var formData = {
reference: {'line1':'something'}, // <- this should work now
lines: [{ // <- this is still an array of objects [{}], as in PHP too, it's a nested array
amount: amount,
'amount_desc': 'amount_desc',
'description': 'description',
'tax_rate': 0,
'price': 100
}]
};
但是,这引起了另一个问题,因为你注意到了。
当我尝试传递这样的对象时:
reference: {'line1':'foo'}
我从Node收到错误:node_modules/request/node_modules/combined-stream/node_modules/delayed-stream/lib/delayed_stream.js:33 source.on('error', function() {}); ^ TypeError: Object #<Object> has no method 'on'
此错误在此解释:https://github.com/request/request/issues/1495
基本上form-data
只需要简单的对象,可能只有1级深。
试试这个:
var formData = {
'reference.line1': 'something',
'lines[0].amount': amount,
'lines[0].amount_desc': 'amount_desc',
'lines[0].description': 'description',
'lines[0].tax_rate': 0,
'lines[0].price': 100,
};