NodeMaster
NodeMaster

Reputation: 85

NPM request form keeps returning 415 status

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?

Upvotes: 0

Views: 57

Answers (1)

Rastalamm
Rastalamm

Reputation: 1792

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

Upvotes: 1

Related Questions