Главная » Ошибки » Stay DRY Using axios for API Requests

Stay DRY Using axios for API Requests

В этой статье

Installation and the basics

It can be installed using npm (or yarn):

npm install axios

An independent POST request using Axios looks like this:

axios.post(‘https://axios-app.firebaseio.com/users.json’, formData)
  .then(res => console.log(res))
  .catch(error => console.log(error))

Native JavaScript has multiple ways of doing JavaScript too. Notably, fetch() . So why use a library at all? Well, for one, error handling in fetch is pretty wonky. You’ll have a better time with axios right out of the gate with that. If you’d like to see a comparison, we have an article that covers both and an article that talks about the value of abstraction with stuff like this.

Another reason to reach for axios? It gives us more opportunities for DRYness, so let’s look into that. 

Global config

We can set up a global configuration (e.g. in our main.js file) that handles all application requests using a standard configuration that is set through a default object that ships with axios. 

This object contains:

  • baseURL: A relative URL that acts as a prefix to all requests, and each request can append the URL
  • хедерs: Custom хедерs that can be set based on the requests
  • timeout: The point at which the request is aborted, usually measured in milliseconds. The default value is 0, meaning it’s not applicable.
  • withCredentials: Indicates whether or not cross-site Access-Control requests should be made using credentials. The default is false.
  • responseType: Indicates the type of data that the server will return, with options including json (default), arraybuffer, document, text, and stream.
  • responseEncoding: Indicates encoding to use for decoding responses. The default value is utf8.
  • xsrfCookieName: The name of the cookie to use as a value for XSRF token, the default value is XSRF-TOKEN.
  • xsrfHeaderName: The name of the HTTP хедер that carries the XSRF token value. The default value is X-XSRF-TOKEN.
  • maxContentLength: Defines the max size of the HTTP response content in bytes allowed
  • maxBodyLength: Defines the max size of the HTTP request content in bytes allowed

Most of time, you’ll only be using baseURL, хедер, and maybe timeout. The rest of them are less frequently needed as they have smart defaults, but it’s nice to know there are there in case you need to fix up requests.

This is the DRYness at work. For each request, we don’t have to repeat the baseURL of our API or repeat important хедерs that we might need on every request. 

Here’s an example where our API has a base, but it also has multiple different endpoints. First, we set up some defaults:

// main.js
import axios from ‘axios’;

axios.defaults.baseURL = ‘https://axios-app.firebaseio.com’ // the prefix of the URL
axios.defaults.хедерs.get[‘Accept’] = ‘application/json’   // default хедер for all get request
axios.defaults.хедерs.post[‘Accept’] = ‘application/json’  // default хедер for all POST request

Then, in a component, we can use axios more succinctly, not needing to set those хедерs, but still having an opportunity to customize the final URL endpoint:

// form.js component
import axios from ‘axios’;

export default {
  methods : {
    onSubmit () {
      // The URL is now https://axios-app.firebaseio.com/users.json
      axios.post(‘/users.json’, formData)
        .then(res => console.log(res))
        .catch(error => console.log(error))
    }
  }
}

Note: This example is in Vue, but the concept extends to any JavaScript situation.

Custom instance

Setting up a “custom instance” is similar to a global config, but scoped to specified components. So, it’s still a DRY technique, but with hierarchy. 

We’ll set up our custom instance in a new file (let’s call it authAxios.js) and import it into the “concern” components.

// authAxios.js
import axios from ‘axios’

const customInstance = axios.create ({
  baseURL : ‘https://axios-app.firebaseio.com’
})
customInstance.defaults.хедерs.post[‘Accept’] = ‘application/json’

// Or like this…
const customInstance = axios.create ({
  baseURL : ‘https://axios-app.firebaseio.com’,
  хедерs: {‘Accept’: ‘application/json’}
})

And then we import this file into the form components:

// form.js component

// import from our custom instance
import axios from ‘./authAxios’

export default {
  methods : {
    onSubmit () {
      axios.post(‘/users.json’, formData)
      .then(res => console.log(res))
      .catch(error => console.log(error))
    }
  }
}

In this guide, you will learn how to design and launch a custom JavaScript API from scratch, sell it, and turn it into a profitable venture.

APIRapidAPI

Mashhood A.

Mashhood A.

Logging Errors

Finally, we can use these properties to log errors properly. It will look like this in code:

jsCopytry{const res =await axios.get(`https://famous-quotes4.p.rapidapi.com/random`);}catch(error){if(error.response){// Request made but the server responded with an error console.log(error.response.data); console.log(error.response.status); console.log(error.response.хедерs);}elseif(error.request){// Request made but no response is received from the server. console.log(error.request);}else{// Error occured while setting up the request console.log(‘Error’, error.message);}}

Now you know how to manage API errors using Axios. Find a suitable API from RapidAPI Hub and integrate it into your projects using Axios.

api# axios# errors#

Как из json файла взять элемент обьекта?

  • 1 подписчик
  • 21 час назад
  • 61 просмотр

ответа
3

  • javascript
    • JavaScript

    • +1 ещё

    Простой

  • Develop a startup with an API: Create and Market an API leveraging JavaScript

    Как стилизовать компоненты React используя методологию BEM?

    • 1 подписчик
    • 21 окт.
    • 70 просмотров

    ответ
    1

  • Показать ещёЗагружается…
  • Вакансии с Хабр Карьеры

    Senior JavaScript Developer (React)

    НЛМК
    •Москва
    от 250 000 ₽

    Frontend разработчик (JavaScript / React)

    QIWI
    •Москва
    от 230 000 ₽

    Senior Frontend Engineer (React, Typescript, Remote, €)

    Apliteni

    от 4 000 €
    Ещё вакансии

    Заказы с Хабр Фриланса

    Копирайтинг

    23 окт. 2022, в 15:35
    4000 руб./за проект

    Таргетолог Вконтакте

    23 окт. 2022, в 15:27
    10000 руб./за проект

    Написать программу на С#

    23 окт. 2022, в 15:11
    4000 руб./за проект
    Ещё заказы

    Минуточку внимания

    Присоединяйтесь к сообществу, чтобы узнавать новое и делиться знаниями

    Зарегистрироваться

    Самое интересное за 24 часа

    • Сущиствует ли GUI фреймворк под windows для rust?

      • 2 подписчика
      • 1 ответ
    • Как выбрать из элемента из списка по его вероятности?

      • 2 подписчика
      • 1 ответ
    • Как получить иностранный номер телефона?

      • 4 подписчика
      • 0 ответов
    • Как удалить вирус, который меняет фон рабочего стола?

      • 4 подписчика
      • 2 ответа
    • Ассемблер в VSCode?

      • 3 подписчика
      • 1 ответ
    • Api через POST запросы?

      • 3 подписчика
      • 2 ответа
    • Проблема с установкой windows что делать?

      • 2 подписчика
      • 1 ответ
    • Как сделать чтобы из моего пакета импортировалось только то, что нужно?

      • 2 подписчика
      • 0 ответов
    • Как сделать рекурсивные списки Visual Prolog?

      • 2 подписчика
      • 0 ответов
    • Безопасен ли зараженный отключенный SSD диск?

      • 2 подписчика
      • 2 ответа
    • © Habr
    • О сервисе
    • Обратная связь
    • Блог

    How to set request хедерs in fetch?

    Почему callback отрабатывает бесконечность раз при клике react?

    • 1 подписчик
    • вчера
    • 33 просмотра

    ответ
    1

  • react
    • React

    Простой

  • Как дождаться данных и выполнить useEffect один раз?

    • 1 подписчик
    • вчера
    • 43 просмотра

    ответа
    2

  • javascript
    • JavaScript

    • +2 ещё

    Средний

  • Subscribe or Follow Me For Updates

    Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

    • Subscribe on YouTube at https://www.youtube.com/JasonWatmore
    • Follow me on Twitter at https://twitter.com/jason_watmore
    • Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
    • Follow me on GitHub at https://github.com/cornflourblue
    • Feed formats available:
      RSS,
      Atom,
      JSON

    Other than coding…

    I’m currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.

    • Subscribe on YouTube at https://www.youtube.com/TinaAndJason
    • Follow us on Instagram at https://www.instagram.com/tinaandjason
    • Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
    • Visit our website at https://tinaandjason.com.au

    Почему не работает код с localStorage?

    • 1 подписчик
    • вчера
    • 68 просмотров

    ответов
    0

  • react
    • React

    Простой

  • POST request using axios with error handling

    This sends a POST request with axios to an invalid url on the api then writes the error message to the parent of the #post-request-error-handling .article-id element and logs the error to the console.

    // POST request using axios with error handling
    const element = document.querySelector(‘#post-request-error-handling .article-id’);
    const article = { title: ‘Axios POST Request Example’ };
    axios.post(‘https://reqres.in/invalid-url’, article)
    .then(response => element.innerHTML = response.data.id )
    .catch(error => {
    element.parentElement.innerHTML = `Error: ${error.message}`;
    console.error(‘There was an error!’, error);
    });

    Example Axios POST request at https://stackblitz.com/edit/axios-http-post-request-examples?file=post-request-error-handling.js

    Как определить тип переменной?

    • 1 подписчик
    • 21 окт.
    • 70 просмотров

    ответов
    0

  • javascript
    • JavaScript

    • +2 ещё

    Простой

  • HTTP хедерs let clients and servers talk to each other and pass extra bits of information. In this piece, let’s learn how to set request хедер in Axios.

    API

    Saad Irfan

    Saad Irfan

    Как сделать чтобы из моего пакета импортировалось только то, что нужно?

    • 2 подписчика
    • 16 часов назад
    • 80 просмотров

    ответов
    0

  • node.js
    • Node.js

    • +2 ещё

    Средний

  • Какая погрешность в количестве фиксаций целевых событий в Яндекс метрике допустима?

    • 2 подписчика
    • 21 окт.
    • 29 просмотров

    ответов
    0

  • css
    • CSS

    • +3 ещё

    Простой

  • Почему не перерисовывается компонент при изменении стейта?

    • 1 подписчик
    • вчера
    • 51 просмотр

    ответ
    1

  • react
    • React

    Простой

  • How to use fetch API in Next.js?

    Почему возникает ошибка при подключении к БД (next js + sequelize)?

    • 1 подписчик
    • 17 часов назад
    • 41 просмотр

    ответ
    1

  • javascript
    • JavaScript

    • +3 ещё

    Простой

  • Simple POST request with a JSON body using axios

    This sends an HTTP POST request to the Reqres api which is a fake online REST api used for testing, it includes a generic /api/ route that supports POST requests to any and responds with the contents of the post body and a dynamic id property. This example sends an article object to the /api/articles route and then writes the id from the response to the #post-request .article-id element so it’s displayed on the page.// Simple POST request with a JSON body using axios
    const element = document.querySelector(‘#post-request .article-id’);
    const article = { title: ‘Axios POST Request Example’ };
    axios.post(‘https://reqres.in/api/articles’, article)
    .then(response => element.innerHTML = response.data.id);

    Example Axios POST request at https://stackblitz.com/edit/axios-http-post-request-examples?file=post-request.js

    Using the RapidAPI VS Code Extension with Python to Create an API

    Read more

    Mashhood A.

    Mashhood A.

    In this guide, you’ll learn how to establish an API-based project using RapidAPI’s new Visual Studio Code extension, which facilitates development and testing.

    APIRapidAPI Client VSCode

    Saad Irfan

    Saad Irfan

    POST request using axios with set HTTP хедерs

    This sends the same POST request again using axios with a couple of хедерs set, the HTTP Authorization хедер and a custom хедер My-Custom-Header.

    // POST request using axios with set хедерs
    const element = document.querySelector(‘#post-request-set-хедерs .article-id’);
    const article = { title: ‘Axios POST Request Example’ };
    const хедерs = {
    ‘Authorization’: ‘Bearer my-token’,
    ‘My-Custom-Header’: ‘foobar’
    };
    axios.post(‘https://reqres.in/api/articles’, article, { хедерs })
    .then(response => element.innerHTML = response.data.id);

    Example Axios POST request at https://stackblitz.com/edit/axios-http-post-request-examples?file=post-request-set-хедерs.js

    Источники

    • https://css-tricks.com/stay-dry-using-axios-for-api-requests/
    • https://rapidapi.com/guides/handle-axios-errors
    • https://qna.habr.com/q/347739
    • https://jasonwatmore.com/post/2021/06/25/axios-http-post-request-examples
    [свернуть]
    Решите Вашу проблему!


    ×
    Adblock
    detector