Sunday, 9 December 2018

nodejs - call REST api with url encoded parameters

I have a REST API that expects url encoded request params as POST request body. So, API schema looks like
POST /login HTTP/1.1
Host: intro-api.com
Accept: */*
Content-Type: application/x-www-form-urlencoded
Content-Length: xxx
And, If you use curl request would look like,
curl -v --request POST -H "Content-Type: application/x-www-form-urlencoded" intro-api.com/login -d 'username=admin' -d 'password=admin'
Also, since content-type is urlencoded type, request params are in query string format. So -d "username=admin&password=admin" is valid as well.

Now,

I have a frontend(html/js) served by nodejs server which would have to validate user login by calling above REST api. This is what I'm talking in this article.
So, first of all I tried standard nodejs http library as a http client. But could not make it work for url encoded params. I was getting 408 error, which means it never sent the params?
function getUserSession(username, password) {

  const postData = qs.stringify({
    'username': username,
    'password': password
  });

  var options = {
    protocol: 'https:',
    host: 'intro.com',
    port: 443,
    path: '/login',
    method: 'POST',
    headers: {
      'Content-Type'  : 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(postData)
    }
  };

  https.request(options, function(resp){
    var response = '';
    resp.on('data', function(chunk){
      response += chunk;
      console.log(response)
    });
  }).on("error", function(e){
    console.log("Got error: " + e.message);
  });

}
So I ended up using request library. which needs to added to package.json (can also be done with npm install request, for more see official documentation).
Next, I will create auth.js with with a function that expects username and password and call the REST api, and respond the cookie value.
var request = require('request');

function getUserSessionId(username, password) {
  console.log("making login request")

  request.post({
    url: 'https://intro.com/login',
    form: {
      username: username,
      password: password
    }
  }).on("response", function(httpResponse) {
        var session = httpResponse.headers['set-cookie']
        console.log("session: " + session)
        return session
  });

}

var token = getUserSessionId('admin', 'admin')
Now, lets run it on terminal using node runtime (without having run it on http)
node auth.js
That is it to call "a REST api with url encoded params" using nodejs.

No comments:

Post a Comment