0

I am trying to make a simple request that was successful in Postman. It's just a POST action with a static URL, Content-Type is application/x-www-form-urlencoded, and two form fields. As simple as this mock example:

enter image description here

However, I can't get the same request working using NPM Request with form:

var apiUrl = "https://myapp.com/myendpoint";
const formData = {
    "user_type": "simple_user",
    "api_key": "123456789XYZ"
}

try {
    request.post({url:apiUrl, formData:formData}, function(err, res, result){
        if (err) {
            console.log(err);
        }
        else {
            console.log(res.statusCode); //always 415
            console.log(result); //always undefined
        }
    });
} catch (err) {
    console.log(err);
}

According to the documentation, I am doing it the right way. Can someone point me to what's wrong?

Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
NodeMaster
  • 85
  • 1
  • 5

1 Answers1

1

According to the documentation the formData key should be form.

Try the below:

try {
    request.post({url:apiUrl, form:formData}, function(err, res, result){
        if (err) {
            console.log(err);
        }
        else {
            // You should have a good response here
        }
    });
} catch (err) {
    console.log(err);
}
Rastalamm
  • 1,712
  • 3
  • 23
  • 32
  • That's strange, in the link to the doc, they used `formData ` instead of `form`, maybe the doc needs to be fixed – NodeMaster Jan 09 '19 at 21:52
  • I think you might be confusing it with [multipart/form-data (Multipart FormUploads)](https://github.com/request/request#multipartform-data-multipart-form-uploads) - for multipart forms it expects `formData`. For `application/x-www-form-urlencoded` it expects `form` – Rastalamm Jan 09 '19 at 22:06