5 Ways to Make HTTP Requests in Node.js
1.HTTP – the Standard Library 2.Request 3.Axios 4.SuperAgent 5.Got
// send a POST request
axios({
method: 'post',
url: '/login',
data: {
firstName: 'Finn',
lastName: 'Williams'
}
});
axios.post('/login', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
Shorthand methods
Axios also provides a set of shorthand methods for performing different types of requests. The methods are as follows:
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
Handling the response
axios.post('/login', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
How the response looks when requesting data from the GitHub API:
axios.get('https://api.github.com/users/mapbox')
.then((response) => {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
// logs:
// => {login: "mapbox", id: 600935, node_id: "MDEyOk9yZ2FuaXphdGlvbjYwMDkzNQ==", avatar_url: "https://avatars1.githubusercontent.com/u/600935?v=4", gravatar_id: "", …}
// => 200
// => OK
// => {x-ratelimit-limit: "60", x-github-media-type: "github.v3", x-ratelimit-remaining: "60", last-modified: "Wed, 01 Aug 2018 02:50:03 GMT", etag: "W/"3062389570cc468e0b474db27046e8c9"", …}
// => {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …}
Making simultaneous requests
This method returns a single promise object that resolves only when all arguments passed as an array have resolved. Here’s a simple example:
// execute simultaneous requests
axios.all([
axios.get('https://api.github.com/users/mapbox'),
axios.get('https://api.github.com/users/phantomjs')
])
.then(responseArr => {
//this will be executed only when all requests are complete
console.log('Date created: ', responseArr[0].data.created_at);
console.log('Date created: ', responseArr[1].data.created_at);
});
// logs:
// => Date created: 2011-02-04T19:02:13Z
// => Date created: 2017-04-03T17:25:46Z
For convenience, Axios also provides a method called axios.spread() to assign the properties of the response array to separate variables.
axios.all([
axios.get('https://api.github.com/users/mapbox'),
axios.get('https://api.github.com/users/phantomjs')
])
.then(axios.spread((user1, user2) => {
console.log('Date created: ', user1.data.created_at);
console.log('Date created: ', user2.data.created_at);
}));
// logs:
// => Date created: 2011-02-04T19:02:13Z
// => Date created: 2017-04-03T17:25:46Z
Sending custom headers
const options = {
headers: {'X-Custom-Header': 'value'}
};
axios.post('/save', { a: 10 }, options);
Transforming requests and responses
To change the request data before sending it to the server, set the transformRequest property in the config object. Note that this method only works for PUT, POST, and PATCH request methods.
const options = {
method: 'post',
url: '/login',
data: {
firstName: 'Finn',
lastName: 'Williams'
},
transformRequest: [(data, headers) => {
// transform the data
return data;
}]
};
// send the request
axios(options);
To modify the data before passing it to then() or catch(), you can set the transformResponse property:
const options = {
method: 'post',
url: '/login',
data: {
firstName: 'Finn',
lastName: 'Williams'
},
transformResponse: [(data) => {
// transform the response
return data;
}]
};
// send the request
axios(options);
Intercepting requests and responses
HTTP Interception is a popular feature of Axios. With this feature, you can examine and change HTTP requests from your program to the server and vice versa, which is very useful for a variety of implicit tasks, such as logging and authentication.
At first glance, interceptors look very much like transforms, but they differ in one key way: unlike transforms, which only receive the data and headers as arguments, interceptors receive the entire response object or request config.
You can declare a request interceptor in Axios like this:
// declare a request interceptor
axios.interceptors.request.use(config => {
// perform a task before the request is sent
console.log('Request was sent');
return config;
}, error => {
// handle the error
return Promise.reject(error);
});
// sent a GET request
axios.get('https://api.github.com/users/mapbox')
.then(response => {
console.log(response.data.created_at);
});
Axios also provides a response interceptor, which allows you to transform the responses from a server on their way back to the application:
// declare a response interceptor
axios.interceptors.response.use((response) => {
// do something with the response data
console.log('Response was received');
return response;
}, error => {
// handle the response error
return Promise.reject(error);
});
// sent a GET request
axios.get('https://api.github.com/users/mapbox')
.then(response => {
console.log(response.data.created_at);
});
Example
Using Request call
var request = require("request");
var email="***@gmail.com"
var token="****.***.***"
var options = {
method: "POST",
uri: "https://api.zoom.us/v2/users/" + email + "/meetings",
body: {
topic: "test create meeting",
type: 1,
settings: {
host_video: "true",
participant_video: "true"
}
},
auth: {
bearer: token
},
headers: {
"User-Agent": "Zoom-api-Jwt-Request",
"content-type": "application/json"
},
json: true //Parse the JSON string in the response
};
let result = await request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log('Body Result : ', body.join_url)
newZoom.join_url=body.join_url
//console.log("newZoom")
//console.log(newZoom)
//console.log("response : ", response)
return newZoom;
});
Using axios call
let newZoom = new models.Zoom();
var email = "***@gmail.com"
var token="****.***.***"
const url = "https://api.zoom.us/v2/users/" + email + "/meetings";
const data = {
topic: "test create meeting",
type: 1,
settings: {
host_video: "true",
participant_video: "true"
}
}
const config = {
headers: { Authorization: `Bearer ${token}`, "User-Agent": "Zoom-api-Jwt-Request", "content-type": "application/json" }
};
const result = await axios.post(url, data, config).then(response => {
newZoom.join_url = response.data.join_url
console.log('newZoom.join_url : ', newZoom.join_url)
return newZoom
}).catch(error => {
//console.log('Zoom Error : ', error)
return error
});
Reference
how-to-make-http-requests-like-a-pro-with-axios
http-requests-in-node-js.html
javascript-async-await
axios-send-authorization-header