2

I'm trying to use an API that accepts the data as form data. In the PHP example I have been given, the working code is as follows using 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. According to the Request docs, using formData will parse an object into the correct format using the FormData library.

I've got this working manually using Postman. Im sending a x-www-form-urlencoded body with fields as:

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);
};
2
  • Which FormData library you are talking about here? Can you add link to the library? Commented Sep 3, 2019 at 13:24
  • Request uses github.com/form-data/form-data. However I think i've just realised that whilst it uses form-data, it doesn't take an array and submit it like I need Commented Sep 3, 2019 at 13:27

2 Answers 2

2

I think you have a typo in the property items which should be item.

The JavaScript code you quoted is actually sending this:

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

While from the PHP code you quoted, it looks like you should send:

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

So I think you should change your example's code to:

const response = await post({item: items}, "http://example.com");
Sign up to request clarification or add additional context in comments.

1 Comment

Ah thats a typo in my copying over the PHP. I have fixed that
0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.