This article shows how to finish HTTPS requests (GET and POST) using the request module on express server. In this case, POST will post a form including credentials to server and returns a bearer token, and the GET method will need bearer token authentication in order to return information.
POST method is used when we would like to change something on the server side. For example, when I request an API token from an REST API, I would want to use the POST method so that every time by making the request I can get a different token. GET method, however, is used when we only want to view contents returned by the server. For example, if I want to grab the data stored in the server, I will use GET method so that the server will return the required contents.
In express environment, we can simply use the request module to help us finish the job. First, install request module by typing “npm i request” in terminal. Then, in your server .js file, require the module by:
const request = require('request') // require request module
In order to finish the POST HTTP request inside a function, use the following code:
function getToken(api_url, user_name, user_password) {
var options = {
url: api_url,
form: {
grant_type: 'password',
username: user_name,
password: user_password
}
}
request.post(options, (error, res, body) => {
if (error) {
console.error(error)
return
}
callback(body); // body will execute after post returns
})
}
Inside the function, the grant type has to be set as “password” for proper authentication. We also use a callback function inside getToken() so that body will get executed after post request returns (This is important because node js is asynchronous, which means post could return after following code get executed).
For calling this function, we use:
getToken('https://xxxxxxxx', [username], [password],
(body) => {
// body stores request response
// will get executed after post request
// you need to handle bad request
access_token = JSON.parse(body).access_token
})
After getting the access token, we can pass it with a GET request to get server side contents. Here’s a function to get contents using Bearer Authentication:
function getContent(get_url, token, callback) {
var bearer_auth = 'Bearer ' + token
var options = {
url: get_url,
headers: {
'Authorization': bearer_auth
},
rejectUnauthorized: false
}
request(options, (err, res, body) => {
if (err) {
console.error(err)
return
} else {
callback(body)
}
})
}
You have to attach “Bearer ” before the token, and use correct header to get the response. To call the function, also include (body) => {} to make sure that body is not empty. GET response is stored inside body.
