我正在使用一个 API,它要求我将一个数组放入表单字段中。给出的示例是用 PHP 编写的,但我使用的是 NodeJS。API 期望其中一个字段是一个数组,我很难弄清楚如何做到这一点。
PHP 示例如下所示:
$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'))
));
在 NodeJS 中,我尝试过这个(除其他外):
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);
}
}
);
当我尝试像这样传递一个对象时:reference: {'line1':'foo'}
我从节点收到一个错误:
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'
我怎样才能最好地把这个圆钉钉在那个方孔里?