3

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.

NodeMaster
  • 85
  • 1
  • 5
  • What does the request look like? What's telling you that this isn't working? Do you have an error message or something? – joshuakcockrell Jan 11 '19 at 22:07
  • 400 unauthorized status @joshuakcockrell – NodeMaster Jan 11 '19 at 22:14
  • Which means it's hitting the server, but the interesting part is I would get 400 on postman as well if I was sending `form-data`, and if I send `x-www-form-urlencoded` then it would succeed in postman. I don't know how to do this in `request` – NodeMaster Jan 11 '19 at 22:16
  • 1
    I'm guessing you don't have control over the server or else you would know more than just a 400 error. Try sending this request to https://httpbin.org/post and it will show you how your request looks to a server. Compare that to a postman request sent to httpbin. This will at least narrow down the problem for you. A 400 error code is pretty generic so you need more info here. – joshuakcockrell Jan 11 '19 at 23:24
  • 1
    Try to skip content-type and use `form: { "field1": value1, "field2": value2 }` instead of body and stringify.. – bigless Jan 11 '19 at 23:36

1 Answers1

0

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

Krimson
  • 7,386
  • 11
  • 60
  • 97