简体   繁体   English

使用请求在 Javascript 中发送表单数据数组?

[英]Sending form data arrays in Javascript using Request?

I'm trying to use an API that accepts the data as form data.我正在尝试使用接受数据作为表单数据的 API。 In the PHP example I have been given, the working code is as follows using GuzzleHttp:在我给出的 PHP 示例中,使用 GuzzleHttp 的工作代码如下:

    $response = $client->post('http://example.com', [
        'headers' => [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $accessToken
        ],
        'form_params' => [
            'items' => $items
        ]
    ])

In my JS, I have the below code.在我的 JS 中,我有以下代码。 According to the Request docs, using formData will parse an object into the correct format using the FormData library.根据请求文档,使用 formData 将使用 FormData 库将对象解析为正确的格式。

I've got this working manually using Postman.我已经使用 Postman 手动完成了这项工作。 Im sending a x-www-form-urlencoded body with fields as:我发送了一个 x-www-form-urlencoded 正文,其中包含以下字段:

item[0] = "abc"
item[1] = "def"

Can anyone see what I'm missing here as to why this isn't working?任何人都可以看到我在这里缺少什么,为什么这不起作用?

const items = ["abc", "def"];
const response = await post({items: items}, "http://example.com")
exports.post = async function (data, url) {
    const token = await getAccessToken();
    const response = await request({
        method: 'POST',
        url: url,
        headers:
            {
                Connection: 'keep-alive',
                Authorization: `Bearer ${token.data.access_token}`,
                Accept: 'application/json',
            },
        formData: data
    });
    return JSON.parse(response);
};

I think you have a typo in the property items which should be item .我认为您在属性items有一个错字,应该是item

The JavaScript code you quoted is actually sending this:您引用的 JavaScript 代码实际上正在发送:

formData: { items: [ 'abc', 'def' ] }

While from the PHP code you quoted, it looks like you should send:从您引用的 PHP 代码来看,您似乎应该发送:

formData: {item: ['abc', 'def']}

So I think you should change your example's code to:所以我认为您应该将示例代码更改为:

const response = await post({item: items}, "http://example.com");

From documentation, it seems that object should be passed instead of array.从文档来看,似乎应该传递对象而不是数组。

var formData = {
  my_field: 'my_value',
  my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
};

request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) {
  if (err) {
    return console.error('upload failed:', err);
  }
  console.log('Upload successful!  Server responded with:', body);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM