Axios HTTP request

Axios HTTP request

Table of contents

No heading

No headings in the article.

Axios is a popular JavaScript library that allows you to make HTTP requests from the browser or from the server. It works in both the browser and in Node.js, and it's designed to be easy to use and flexible.

Over the years axios has gained wider acceptance over fetch based on a few considerations.

There are a few reasons why you might want to use Axios over the built-in fetch function in JavaScript:

1.Axios is a promise-based library, which means you can use async/await syntax to make your code more readable and easier to write.

2.Axios can automatically transform the response data into JSON, which is convenient if you're working with APIs that return JSON data.

3.Axios has a number of built-in features for handling common HTTP scenarios, such as setting default headers, and retrying failed requests.

4. Axios has a larger community and more extensive documentation, which means it's more likely to have solutions to common problems and more resources available to help you learn how to use it.

That being said, fetch is a perfectly fine choice for making HTTP requests and has some benefits of its own. For example, it's a built-in function that is available in all modern browsers, so you don't have to install any additional libraries. Additionally, fetch is a lower-level API that gives you more control over the details of the request and response.

Ultimately, the choice between fetch and Axios comes down to personal preference and the specific needs of your project. Both are good options and can be used effectively in the right context.

For the sake of this tutorial we'll be considering the axios library.

To use Axios, you can install it from npm by running the following command:

npm install axios

You can then import it into your project and use it like this:

import axios from 'axios';

const fetchData = async () => {

try{

const response = await axios.get('https://myapi.com/endpoint'); console.log(response.data);

}

catch (error) { console.error(error)} }

fetchData();

In this example, we are making a GET request to the specified endpoint using Axios. If the request is successful, the response data will be logged to the console. If there is an error, it will be caught and logged to the console.

One of the nice things about Axios is that it allows you to set default configurations for all your requests. For example, you can set the base URL for your API, or you can specify that all your requests should include an authorization header. Here's an example of how you can set default configurations:

axios.defaults.baseURL = 'https://myapi.com'; axios.defaults.headers.common['Authorization'] = 'Bearer MY_TOKEN';

You can also use Axios to make POST, PUT, and DELETE requests, as well as send data in the request body or in the query string. Here's an example of a POST request:

const createData = async () => {

try {

const response = await axios.post('https://myapi.com/endpoint', { name: 'John', age: 30 }); console.log(response.data);

}

catch (error) { console.error(error) } }

createData();

In this example, we are making a POST request to the specified endpoint with a JSON payload in the request body. If the request is successful, the response data will be logged to the console.

Here's an example of making a PUT request to update a resource

const setData = async () => {

try{

const response = await axios.put('https://myapi.com/user/123', { firstName: 'John', lastName: 'Doe' }) console.log(response.data);

}

catch(error){console.error(error)} }

setData();

In this example we are updating the users record on the database using a PUT request, the /user/123 part of the URL is the resource that you want to update. The PUT request includes a JSON object with the updated data for the resource.

And here's an example of how you can make a DELETE request to delete a resource:

const deleteData = async () => {

try{

const response = await axios.delete('https://myapi.com/user/123') console.log(response.data)console.log(response.data));

}

catch(error){console.error(error)} }

deleteData();

In this example we are deleting a user from the database using a DELETE request, the /user/123 part of the URL is the resource that you want to delete. The DELETE request does not include a request body.

You can also pass additional options as a second argument to the put and delete methods, such as the headers or params options, if you need to specify them.

I hope this helps give you a basic understanding of how to use Axios for making HTTP requests. Let me know if you have any questions or need further information.