How to use Native Fetch API in Node
Table of Contents
For a long time, making requests on Node required a third-party library like Axios or node-fetch
However, now Node has the same fetch API found on browsers, meaning we can use the native fetch API to make requests.
In this article, we'll look at how to use the fetch API to make requests on Node.
Making a request
To make a request, we can use the fetch function, just like on browsers:
JAVASCRIPTconst request = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const response = await request.json();
console.log(response);
We are making use of await/async to wait for the response to be returned, then we are parsing the response as JSON.
We can easily check the status of the request by checking the ok
property:
JAVASCRIPTconst request = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (!request.ok) {
// handle issue
}
Making a POST request is also very straight-forward, just pass in an options argument to the fetch function:
JAVASCRIPTconst options = {
method: "POST",
body: JSON.stringify({
title: "foo",
body: "bar",
userId: 1,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
}
};
const request = await fetch("https://jsonplaceholder.typicode.com/todos", options);
const response = await request.json();
console.log(response);
Now, if you want to handle any exceptions, just wrap this inside of a try-catch:
JAVASCRIPTtry {
const request = await fetch("https://jsonplaceholder.typicode.com/todos/1");
if (!request.ok) {
// handle issue
}
} catch (error) {
// handle error
}
Conclusion
In this post, we learned how to use the native fetch API to make requests on Node.
We can now use this API and get rid of any third-party libraries that do essentially the same thing.
Thanks for reading!
- Getting Started with Solid
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Setting Up Stylus CSS Preprocessor