javascriptnode.jsrequestnode-requestnpm-request

How to send bearer token and x-www-form-urlencoded data using Node Request


I want to replicate this Postman call using the node module request. See screenshots.

Screenshot

Screenshot2

As shown in screenshot, in my request, I need to pass a bearer token as well as x-www-form-urlencoded values. I tried following the top 2 answers from this SO post but with no success.

I have basically tried doing

let form = {
    "field1": value1,
    "filed2": value2
};

let headers = {
    'Content-Type' : 'application/x-www-form-urlencoded',
    'Authorization': 'Bearer ' + token
}

request.post({ url: "https://myapp.net/myendpoint", form: form, headers: headers }, function(err, res, success){
    console.log(success);
});

and also

let form = {
    "field1": value1,
    "field2": value2
};

var formData = querystring.stringify(form);

let options = {
    uri: "https://myapp.net/myendpoint",
    method: 'POST',
    auth: {
        'bearer': token
    },
    headers: {
        'Content-Type' : 'application/x-www-form-urlencoded'
    },
    body: formData
};


request.post(options, function(err, res, success){
    console.log(success);
});

Can someone please show the right way to do it?

EDIT: To clarify: the result of these requests is 400 status. I would get 400 on Postman as well if I was sending form-data, but if I send x-www-form-urlencoded then it would succeed in postman. I don't know how to do this in request.


Solution

  • Try this

    let options = {
        uri: "https://myapp.net/myendpoint",
        method: 'POST',
        headers: {
            'Authorization' : 'Bearer ' + token
        },
        form: {
            "field1": value1,
            "field2": value2
        };
    };
    
    request.post(options, function(err, res, success){
        console.log(success);
    });
    

    The content type should be set automatically