I’m trying to understand javascript promises better with Axios. What I pretend is to handle all errors in Request.js and only call the request function from anywhere without having to use catch().
In this example, the response to the request will be 400 with an error message in JSON.
This is the error I’m getting:
Uncaught (in promise) Error: Request failed with status code 400
The only solution I find is to add .catch(() => {}) in Somewhere.js but I’m trying to avoid having to do that. Is it possible?
Here’s the code:
Request.js
export function request(method, uri, body, headers) {
let config = {
method: method.toLowerCase(),
url: uri,
baseURL: API_URL,
headers: { 'Authorization': 'Bearer ' + getToken() },
validateStatus: function (status) {
return status >= 200 && status < 400
}
}
...
return axios(config).then(
function (response) {
return response.data
}
).catch(
function (error) {
console.log('Show error notification!')
return Promise.reject(error)
}
)
}
Somewhere.js
export default class Somewhere extends React.Component {
...
callSomeRequest() {
request('DELETE', '/some/request').then(
() => {
console.log('Request successful!')
}
)
}
...
}
asked Apr 22, 2018 at 15:45
4
Actually, it’s not possible with axios as of now. The status codes which falls in the range of 2xx only, can be caught in .then().
A conventional approach is to catch errors in the catch() block like below:
axios.get('/api/xyz/abcd')
.catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
Another approach can be intercepting requests or responses before they are handled by then or catch.
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
answered Aug 9, 2018 at 13:26
![]()
Plabon DuttaPlabon Dutta
6,5193 gold badges28 silver badges32 bronze badges
7
If you want to gain access to the whole the error body, do it as shown below:
async function login(reqBody) {
try {
let res = await Axios({
method: 'post',
url: 'https://myApi.com/path/to/endpoint',
data: reqBody
});
let data = res.data;
return data;
} catch (error) {
console.log(error.response); // this is the main part. Use the response property from the error object
return error.response;
}
}
answered Mar 24, 2020 at 5:22
![]()
elonaireelonaire
1,7481 gold badge9 silver badges16 bronze badges
1
You can go like this:
error.response.data
In my case, I got error property from backend. So, I used error.response.data.error
My code:
axios
.get(`${API_BASE_URL}/students`)
.then(response => {
return response.data
})
.then(data => {
console.log(data)
})
.catch(error => {
console.log(error.response.data.error)
})
answered Mar 26, 2020 at 14:08
![]()
0
If you wan’t to use async await try
export const post = async ( link,data ) => {
const option = {
method: 'post',
url: `${URL}${link}`,
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
data
};
try {
const response = await axios(option);
} catch (error) {
const { response } = error;
const { request, ...errorObject } = response; // take everything but 'request'
console.log(errorObject);
}
Ben T
4,4663 gold badges21 silver badges22 bronze badges
answered Oct 16, 2019 at 15:59
user4920718user4920718
1,0151 gold badge9 silver badges12 bronze badges
1
I tried using the try{}catch{} method but it did not work for me. However, when I switched to using .then(...).catch(...), the AxiosError is caught correctly that I can play around with. When I try the former when putting a breakpoint, it does not allow me to see the AxiosError and instead, says to me that the caught error is undefined, which is also what eventually gets displayed in the UI.
Not sure why this happens I find it very trivial. Either way due to this, I suggest using the conventional .then(...).catch(...) method mentioned above to avoid throwing undefined errors to the user.
![]()
Dharman♦
29.2k21 gold badges79 silver badges131 bronze badges
answered Feb 2, 2021 at 8:02
![]()
1
For reusability:
create a file errorHandler.js:
export const errorHandler = (error) => {
const { request, response } = error;
if (response) {
const { message } = response.data;
const status = response.status;
return {
message,
status,
};
} else if (request) {
//request sent but no response received
return {
message: "server time out",
status: 503,
};
} else {
// Something happened in setting up the request that triggered an Error
return { message: "opps! something went wrong while setting up request" };
}
};
Then, whenever you catch error for axios:
Just import error handler from errorHandler.js and use like this.
try {
//your API calls
} catch (error) {
const { message: errorMessage } = errorHandlerForAction(error);
//grab message
}
answered Jan 12, 2022 at 15:51
![]()
If I understand correctly you want then of the request function to be called only if request is successful, and you want to ignore errors. To do that you can create a new promise resolve it when axios request is successful and never reject it in case of failure.
Updated code would look something like this:
export function request(method, uri, body, headers) {
let config = {
method: method.toLowerCase(),
url: uri,
baseURL: API_URL,
headers: { 'Authorization': 'Bearer ' + getToken() },
validateStatus: function (status) {
return status >= 200 && status < 400
}
}
return new Promise(function(resolve, reject) {
axios(config).then(
function (response) {
resolve(response.data)
}
).catch(
function (error) {
console.log('Show error notification!')
}
)
});
}
answered Feb 10, 2021 at 22:19
Damir MiladinovDamir Miladinov
1,0741 gold badge10 silver badges15 bronze badges
1
https://stackabuse.com/handling-errors-with-axios/
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
} else if (err.request) {
// The client never received a response, and the request was never left
} else {
// Anything else
}
}
try {
let res = await axios.get('/my-api-route');
// Work with the response...
} catch (err) {
if (err.response) {
// The client was given an error response (5xx, 4xx)
} else if (err.request) {
// The client never received a response, and the request was never left
console.log(err.request);
} else {
// Anything else
}
}
answered Jun 6, 2022 at 7:50
![]()
call the request function from anywhere without having to use catch().
First, while handling most errors in one place is a good Idea, it’s not that easy with requests. Some errors (e.g. 400 validation errors like: «username taken» or «invalid email») should be passed on.
So we now use a Promise based function:
const baseRequest = async (method: string, url: string, data: ?{}) =>
new Promise<{ data: any }>((resolve, reject) => {
const requestConfig: any = {
method,
data,
timeout: 10000,
url,
headers: {},
};
try {
const response = await axios(requestConfig);
// Request Succeeded!
resolve(response);
} catch (error) {
// Request Failed!
if (error.response) {
// Request made and server responded
reject(response);
} else if (error.request) {
// The request was made but no response was received
reject(response);
} else {
// Something happened in setting up the request that triggered an Error
reject(response);
}
}
};
you can then use the request like
try {
response = await baseRequest('GET', 'https://myApi.com/path/to/endpoint')
} catch (error) {
// either handle errors or don't
}
answered Feb 24, 2020 at 12:35
![]()
David SchumannDavid Schumann
12.7k8 gold badges70 silver badges89 bronze badges
2
One way of handling axios error for response type set to stream that worked for me.
.....
.....
try{
.....
.....
// make request with responseType: 'stream'
const url = "your url";
const response = axios.get(url, { responseType: "stream" });
// If everything OK, pipe to a file or whatever you intended to do
// with the response stream
.....
.....
} catch(err){
// Verify it's axios error
if(axios.isAxios(err)){
let errorString = "";
const streamError = await new Promise((resolve, reject) => {
err.response.data
.on("data", (chunk) => {
errorString += chunk;
}
.on("end", () => {
resolve(errorString);
}
});
// your stream error is stored at variable streamError.
// If your string is JSON string, then parse it like this
const jsonStreamError = JSON.parse(streamError as string);
console.log({ jsonStreamError })
// or do what you usually do with your error message
.....
.....
}
.....
.....
}
answered Oct 10, 2021 at 8:58
![]()
BikashBikash
1601 silver badge6 bronze badges
If I understand you correctly, you want some kind of global handler, so you don’t have to attach a catch handler to every request you make. There is a window event for that called unhandledrejection.
You can read more about this Event in the official documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event
Here is how you can attach a listener for this Event:
window.addEventListener('unhandledrejection', (event) => {
// Handle errors here...
});
answered Dec 1, 2022 at 9:15
DavidDavid
516 bronze badges
axios
Клиент для HTTP-запросов для браузера и Node.JS, построенный на Promise
Отличительные особенности
- Отправка XMLHttpRequests из браузера
- HTTP запросы из NodeJS
- Полная поддержка Promise API
- Перехват запросов и ответов
- Преобразование получаемых и принимаемых данных
- Отмена запроса
- Автоматическое преобразование JSON
- Защита на стороне клиента от CSRF-атак
Browser Support
| Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ |
Установка
посредством npm (у вас должен быть установлен пакет Node JS ссылка )
c помощью менеджера пакетов bower
используя ссылку на CDN, которую можно разместить непосредственно на странице
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Примеры использования
GET — запрос
// делаем GET запрос чтобы получить пользователя (user) // с указанным параметром ID = 12345 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // так же, параметры можно передавать отдельно, в виде объекта // схема ('url', params), где params объект axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // Хотите использовать async/await? Не проблема! Добавьте "async" - перед вашим методом/функуцей, // и await перед самими запросом. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } }
FOX:async/await— часть нового стандарта ECMAScript 2017. Этот функционал не поддерживается IE и некоторыми старыми браузерами.
Почитать на русском можно здесь
Также можно использовать BABEL для транспиляции(перевода) кода к стандарту ES5, который имеет практически полную совместимость с браузерами
POST — запрос
FOX обратите внимание, что зачастую в POST запросе требуется что-то отправлять: объект с параметрами, пустой объект или что-либо еще.
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
FOX в стандарте ES6 вышеуказанный код выглядел бы так(применим стрелочную функцию).
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(response => console.log(response)); .catch(error => console.log(error));
FOX Согласитесь, так выглядит лаконичнее. Более детально о новых фишках в ES6 можно прочесть тут — https://learn.javascript.ru/es-modern
Несколько запросов одновременно
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Оба запроса завершены }));
Axios API
FOX Запросы могут быть выполнены путем передачи параметров/настроек в axios(config). То есть вместо стандартноq схемы axios.get('http://yourlink.com/api', parameters) вы указываете каждый параметр(ссылка, объект для передачи, метод и т.д.) вручную. Иногда это может быть удобно, но если Вам нужно просто отправить небольшой запрос и получить данные, воспользуйтесь стандартной схемой(см. раздел GET-запрос)
// отправка POST запроса axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
// отправка GET запроса для получения изображения // со стороннего сервера axios({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }) .then(function(response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) });
axios(url[, config])
// отправка GET запроса с параметрами по умолчанию axios('/user/12345');
Встроенные методы HTTP запросов
Для Вашего удобства были созданы методы для всех поддерживаемых типов запросов.
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]])
FOXиспользуя данные методы, Вам необязательно указывать свойстваmethodиdataв настройках.
Мультизапросы
Вспомогательные функции для того чтобы использовать несколько запросов одновременно
axios.all(iterable)
axios.spread(callback)
Cоздание нового экземпляра Axios
Вы можете создать новый экземпляр(образец) Axios cо своими настройками
axios.create([config])
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
Методы экземпляра
Доступные методы экземпляра(образца) Axios перечислены ниже. Указанные настройки в них будут объединены с конфигурацией экземпляра.
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]])
Настройка запросов
Это параметры для запросов. Если тип запроса не указан, то по умолчанию будет выполняться GET запрос. Запросы указываются при вызове метода, в объекте.
пример: axios.get(params), где params настройки
{ // `url` - адрес сервера. куда отправляется запрос url: '/user', // `method` тип http-запроса (get, post, delete и т.д.) method: 'get', // default // `baseURL` будет добавлен к `url`, если `url` не будет абсолютным. // это может быть удобным - установить `baseURL` для экземпляра axios для передачи // относительных URL-адресов. // установив единожды в настйроках 'baseURL' не нужно будет указывать полный адрес при запросе. baseURL: 'https://some-domain.com/api/', // `transformRequest` позволяет изменять данные запроса до его отправки на сервер // Это применимо только для методов запроса «PUT», «POST» и «PATCH» // Последняя функция в массиве должна возвращать строку или экземпляр типа Buffer, ArrayBuffer, // FormData или Stream // Также вы можете изменить объект заголовков. transformRequest: [function (data, headers) { // тут пишем код для обработки данных... return data; }], // `transformResponse` позволяет изменять данные ответа, (аналог вышеуказанному методу) // но уже для запроса. редультат передается в then / catch transformResponse: [function (data) { // тут пишем код для обработки данных... return data; }], // `headers` - указываем тут заголовки для запроса headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` - параметры URL, которые обычно указываются в адресе запроса // параметры должны быть указаны в виде обычного объекта JS params: { ID: 12345 }, // `paramsSerializer` - метод для сериализации(обработки) параметров // (https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` - данные, которые должны быть отправлены в теле запроса // Применяется только доя методов 'PUT', 'POST', and 'PATCH' // Если параметр `transformRequest` не установлен, то тело запроса может быть следующих типов: // - string, object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Для браузера: FormData, File, Blob // - Для Node JS: Stream, Buffer data: { firstName: 'Fred' }, // `timeout` количество миллисекунд до истечения времени ожидания запроса. // Если запрос занимает больше времени, чем `timeout`, он будет прерван. timeout: 1000, // `withCredentials` - отображает статус CORS запросов - то есть должны ли запрошиваться // необходимые парметры или нет. Подробнее тут - https://developer.mozilla.org/ru/docs/Web/HTTP/CORS withCredentials: false, // default // `adapter` - позволяет делать доп.настройку запросов, что облегчает тестирование. // Возвращает Promise и валидный ответ (подробнее в lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` указывает, необходимо ли использовать HTTP Basic auth и предоставлять учетные данные. // ВНИМАНИЕ! Этот параметр установит в запрос заголовок `Authorization`, перезаписав все существующие // пользовательские заголовки `Authorization`, которые вы задали в настройках // с помощью параметра - 'headers` auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` указывает тип данных, которыми ответит сервер // варианты: «arraybuffer», «blob», «document», «json», «text», «stream», responseType: 'json', // по умолчанию // `responseEncoding` указывает какую кодировку использовать для обработки ответов // Примечание: Игнорируется для опции `responseType` - 'stream'(поток) или запросов на стороне клиента, // что вполне логично, так как потоковые данные и должны так передаваться responseEncoding: 'utf8', // default //`xsrfCookieName` - имя cookie для использования в качестве значения для токена xsrf xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` http-заголовко для использования в качестве значения для токена xsrf xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` позволяет обрабатывать события прогресса для загрузки данных // например тут можно "повесить" индикатор загружки данных на сервер onUploadProgress: function (progressEvent) { // делаем тут что угодно... }, // `onDownloadProgress` позволяет обрабатывать события прогресса скачивания данных // как вариант - разместить здесь индикацию размера скачиваемого файла onDownloadProgress: function (progressEvent) { // делаем тут что угодно... }, // `maxContentLength` определяет максимальный размер содержимого ответа HTTP в байтах maxContentLength: 2000, // `validateStatus` определяет, разрешать или отклонять Prоmise для данного // HTTP-ответа. Если `validateStatus` возвращает` true` (или установлен в `null` // или `undefined`), Promise будет выполнен; в противном случае отклонен validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` - максимальное количество редиректов в node.js. // если значение устанвлено в "0" - редиректа не будет maxRedirects: 5, // default // `socketPath` определяет UNIX Socket для использования в node.js. // например. '/var/run/docker.sock' для отправки запросов демону docker. // Можно указать только «socketPath» или «proxy». // Если оба указаны, используется `socketPath`. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. // `httpAgent` и` httpsAgent` - установка своего `httpAgent`, который будет использоваться // при выполнении http и https-запросов. Соответственно, в node.js. // Это позволяет добавлять опции (например `keepAlive`), которые по умолчанию не включены. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' определяет имя хоста и порт прокси-сервера // Используйте `false` для отключения прокси при запросах, игнорируя глобальные среды. // `auth` указывает, что для подключения к прокси следует использовать HTTP Basic auth и // предоставляет учетные данные. // Эта опция установит заголовок `Proxy-Authorization`, переписывая любые существующие // `Proxy-Authorization` заголовки, которые вы задали в` headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` указывает токен, который может использоваться для отмены запроса cancelToken: new CancelToken(function (cancel) { }) }
Схема ответа
Ответ на запрос содержит следующие параметры:
{ // `data` - собственно данные ответа от сервера тут data: {}, // `status` HTTP код ответа от сервера // полный список тут - https://developer.mozilla.org/ru/docs/Web/HTTP/Status status: 200, // `statusText` - текст сообщение ответа от сервера statusText: 'OK', // `headers` - заголовки ответа от сервера. headers: {}, // `config` - это конфигурация `axios` для запроса config: {}, // `request` - это запрос, который сгенерировал этот ответ // Это последний экземпляр ClientRequest в node.js (в переадресации) // и экземпляр XMLHttpRequest в браузере request: {} }
Используя then можно посмотреть ответ таким образом:
axios.get('/user/12345') .then(function(response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); });
При использовании catch или передачи rejection callback(callback для отмены) в качестве 2-го параметра then, ответ будет доступен через объект error, как описано в разделе Обработка ошибок
Настройки по умолчанию
Вы можете указать настройки по умолчанию, которые будут применяться к каждому запросу.
Глобальные переменные в Axios
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Пользовательские настройки для экземплара
// Установка дефолтных настроек при создании экземпляра const instance = axios.create({ baseURL: 'https://api.example.com' }); // Устанавливаем значения по умолчанию после создания экземпляра instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Настройка приоритета
Конфигурация будет объединена с порядком приоритета. Порядок — это значения по умолчанию в библиотеке, найденные в lib/defaults.js, затем свойство defaults экземпляра и наконец, аргумент config для запроса. Последний будет иметь приоритет над первым. Вот пример
// Создаем образец используя настройки по умолчанию предоставленные библиотекой // На этом этапе значение конфигурации тайм-аута равно `0`, как по умолчанию для библиотеки const instance = axios.create(); // Завершение таймаута по умолчанию для библиотеки // Теперь все запросы с использованием этого экземпляра будут ждать 2,5 секунды до истечения времени ожидания instance.defaults.timeout = 2500; // Завершение таймаута для этого запроса, поскольку, он занимает много времени instance.get('/longRequest', { timeout: 5000 });
Перехватчики
Вы можете перехватить запросы или ответы непосредственно перед тем, как они будут обработаны then или catch.
// Добавление перехвата запроса axios.interceptors.request.use(function (config) { // делаем что угодно перед запросом return config; }, function (error) { // обрабатываем ошибку return Promise.reject(error); }); // Добавляем перехватчик ответа axios.interceptors.response.use(function (response) { // Делаем что угодно с поступившими данными return response; }, function (error) { // Обрабатываем ошибку return Promise.reject(error); });
Если позднее Вам нужно будет удалить перехватчик, Вы можете сделать следующее:
const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
Также, Вы можете добавлять перехватчики в свой экземпляр axios
const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/});
Обработка ошибок
axios.get('/user/12345') .catch(function (error) { if (error.response) { // Запрос выполнен, и сервер отправил Вам статус код // код выпададет из диапазона 2хх (ошибка) console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // Запрос был сделан, но ответ не получен // `error.request` - экземпляр XMLHttpRequest в браузере, // http.ClientRequest экземпляр в node.js console.log(error.request); } else { // Что-то пошло не так, вернулась ошибка console.log('Error', error.message); } console.log(error.config); });
Вы можете определить свой диапазон ошибок кода состояния HTTP, используя опцию конфигурации validateStatus.
Например, можно настроить так, что все ошибки с кодом в диапазоне 2хх-3хх будут игонирироваться. В реальности это конечно не пригодится, но возможность такая есть
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // остановить запрос, только если код больше или равен 500 } })
Отмена запроса
Вы можете отменить запрос, используя cancel token.
Token для отмены запросов в Axios базируется на cancelable promises proposal.
Вы можете создать token отмены с помощью фабричной функции CancelToken.source, как показано ниже:
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // обработка ошибок } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // отмена запроса (отображение сообщения можно настроить дополнительно) source.cancel('Operation canceled by the user.');
Вы также можете создать token для отмены запроса, передав функцию конструктору CancelToken:
const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // исполняемая функция получает функцию отмены в качестве параметра cancel = c; }) }); // отмена запроса cancel();
Примечание. Вы можете отменить несколько запросов одним токеном(cancell token).
Использование формата application/x-www-form-urlencoded
По умолчанию axios переводит объекты JavaScript в JSON. Чтобы отправить данные в формате application/x-www-form-urlencoded, Вы можете использовать один из следующих вариантов.
Браузер
В браузере Вы можете испольприменить API URLSearchParams следующим образом:
const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);
Обратите внимание, что
URLSearchParamsподдерживается не всеми браузерами (см. Caniuse.com), но существует полифилл
Кроме того, вы можете декодировать данные, используя библиотеку qs:
const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 }));
Или по-другому… (ES6),
import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options);
Node JS
В Node JS Вы можете использовать модуль querystring так:
const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
Вы также можете использовать библиотеку qs.
О версиях…
До тех пор, пока Axios не достигнет версии «1.0», серьезные изменения автором данной библиотеки будут выпущены лишь с новой минорной версией. Например, 0.5.1 и 0.5.4 будут иметь один и тот же API, но версия 0.6.0 будет иметь в своем составе уже серьезные доработки.
Promises / Промисы
Работа axios напрямую зависит от поддержки Promise. Проверить подержку клиентами(браузерами) можно на сайте can i use.
Если Promise не поддерживаются, можно использовать полифилл/polyfill.
Более подробно почитать о Promise на русском можно тут:
- Learn JS
- Руководство
- Промисы на примерах из жизни
- Promise для новичков
TypeScript
Axios и TypeScript работают вместе
import axios from 'axios'; axios.get('/user?ID=12345');
Дополнительная информация
- Изменения
- Руководство по обновлению
- Экосистема
- Руководство для участников
- Кодекс поведения
Респект…
Создатели Axios были вдохновлены $http-service, который есть в Ангуляре / AngularJS. В конечном счете, axios — это попытка дать возможность использовать эту замечатульную фичу Ангуляра за его пределами
Лицензия
MIT
Introduction
I really love the problem/solution. approach. We see some problem, and then, a really nice solution. But for this talking, i think we need some introduction as well.
When you develop an web application, you generally want’s to separate the frontend and backend. Fo that, you need something that makes the communication between these guys.
To illustrate, you can build a frontend (commonly named as GUI or user interface) using vanilla HTML, CSS and Javascript, or, frequently, using several frameworks like Vue, React and so many more avaliable online. I marked Vue because it’s my personal preference.
Why? I really don’t study the others so deeply that i can’t assure to you that Vue is the best, but i liked the way he works, the syntax, and so on. It’s like your crush, it’s a personal choice.
But, beside that, any framework you use, you will face the same problem:_ How to communicate with you backend_ (that can be written in so many languages, that i will not dare mention some. My current crush? Python an Flask).
One solution is to use AJAX (What is AJAX? Asynchronous JavaScript And XML). You can use XMLHttpRequest directly, to make requests to backend and get the data you need, but the downside is that the code is verbose. You can use Fetch API that will make an abstraction on top of XMLHttpRequest, with a powerfull set of tools. Other great change is that Fetch API will use Promises, avoiding the callbacks from XMLHttpRequest (preventing the callback hell).
Alternatively, we have a awesome library named Axios, that have a nice API (for curiosity purposes, under the hood, uses XMLHttpRequest, giving a very wide browser support). The Axios API wraps the XMLHttpRequest into Promises, different from Fetch API. Beside that, nowadays Fetch API is well supported by the browsers engines available, and have polyfills for older browsers. I will not discuss which one is better because i really think is personal preference, like any other library or framework around. If you dont’t have an opinion, i suggest that you seek some comparisons and dive deep articles. Has a nice article that i will mention to you written by Faraz Kelhini.
My personal choice is Axios because have a nice API, has Response timeout, automatic JSON transformation, and Interceptors (we will use them in the proposal solution), and so much more. Nothing that cannot be accomplished by Fetch API, but has another approach.
The Problem
Talking about Axios, a simple GET HTTP request can be made with these lines of code:
import axios from 'axios'
//here we have an generic interface with basic structure of a api response:
interface HttpResponse<T> {
data: T[]
}
// the user interface, that represents a user in the system
interface User {
id: number
email: string
name: string
}
//the http call to Axios
axios.get<HttpResponse<User>>('/users').then((response) => {
const userList = response.data
console.log(userList)
})
Enter fullscreen mode
Exit fullscreen mode
We’ve used Typescript (interfaces, and generics), ES6 Modules, Promises, Axios and Arrow Functions. We will not touch them deeply, and will presume that you already know about them.
So, in the above code, if everything goes well, aka: the server is online, the network is working perfectly, so on, when you run this code you will see the list of users on console. The real life isn’t always perfect.
We, developers, have a mission:
Make the life of users simple!
So, when something is go bad, we need to use all the efforts in ours hands to resolve the problem ourselves, without the user even notice, and, when nothing more can be done, we have the obligation to show them a really nice message explaining what goes wrong, to easy theirs souls.
Axios like Fetch API uses Promises to handle asynchronous calls and avoid the callbacks that we mention before. Promises are a really nice API and not to difficult to understand. We can chain actions (then) and error handlers (catch) one after another, and the API will call them in order. If an Error occurs in the Promise, the nearest catch is found and executed.
So, the code above with basic error handler will become:
import axios from 'axios'
//..here go the types, equal above sample.
//here we call axios and passes generic get with HttpResponse<User>.
axios
.get<HttpResponse<User>>('/users')
.then((response) => {
const userList = response.data
console.log(userList)
})
.catch((error) => {
//try to fix the error or
//notify the users about somenthing went wrong
console.log(error.message)
})
Enter fullscreen mode
Exit fullscreen mode
Ok, and what is the problem then? Well, we have a hundred errors that, in every API call, the solution/message is the same. For curiosity, Axios show us a little list of them: ERR_FR_TOO_MANY_REDIRECTS, ERR_BAD_OPTION_VALUE, ERR_BAD_OPTION, ERR_NETWORK, ERR_DEPRECATED, ERR_BAD_RESPONSE, ERR_BAD_REQUEST, ERR_CANCELED, ECONNABORTED, ETIMEDOUT. We have the HTTP Status Codes, where we found so many errors, like 404 (Page Not Found), and so on. You get the picture. We have too much common errors to elegantly handle in every API request.
The very ugly solution
One very ugly solution that we can think of, is to write one big ass function that we increment every new error we found. Besides the ugliness of this approach, it will work, if you and your team remember to call the function in every API request.
function httpErrorHandler(error) {
if (error === null) throw new Error('Unrecoverable error!! Error is null!')
if (axios.isAxiosError(error)) {
//here we have a type guard check, error inside this if will be treated as AxiosError
const response = error?.response
const request = error?.request
const config = error?.config //here we have access the config used to make the api call (we can make a retry using this conf)
if (error.code === 'ERR_NETWORK') {
console.log('connection problems..')
} else if (error.code === 'ERR_CANCELED') {
console.log('connection canceled..')
}
if (response) {
//The request was made and the server responded with a status code that falls out of the range of 2xx the http status code mentioned above
const statusCode = response?.status
if (statusCode === 404) {
console.log('The requested resource does not exist or has been deleted')
} else if (statusCode === 401) {
console.log('Please login to access this resource')
//redirect user to login
}
} else if (request) {
//The request was made but no response was received, `error.request` is an instance of XMLHttpRequest in the browser and an instance of http.ClientRequest in Node.js
}
}
//Something happened in setting up the request and triggered an Error
console.log(error.message)
}
Enter fullscreen mode
Exit fullscreen mode
With our magical badass function in place, we can use it like that:
import axios from 'axios'
axios
.get('/users')
.then((response) => {
const userList = response.data
console.log(userList)
})
.catch(httpErrorHandler)
Enter fullscreen mode
Exit fullscreen mode
We have to remember to add this catch in every API call, and, for every new error that we can graciously handle, we need to increase our nasty httpErrorHandler with some more code and ugly if's.
Other problem we have with this approach, besides ugliness and lack of mantenability, is that, if in one, only single one API call, i desire to handle different from global approach, i cannot do.
The function will grow exponentially as the problems that came together. This solution will not scale right!
The elegant and recommended solution
When we work as a team, to make them remember the slickness of every piece of software is hard, very hard. Team members, come and go, and i do not know any documentation good enough to surpass this issue.
In other hand, if the code itself can handle these problems on a generic way, do-it! The developers cannot make mistakes if they need do nothing!
Before we jump into code (that is what we expect from this article), i have the need to speak some stuff to you understand what the codes do.
Axios allow we to use something called Interceptors that will be executed in every request you make. It’s a awesome way of checking permission, add some header that need to be present, like a token, and preprocess responses, reducing the amount of boilerplate code.
We have two types of Interceptors. Before (request) and After (response) an AJAX Call.
It’s use is simple as that:
//Intercept before request is made, usually used to add some header, like an auth
const axiosDefaults = {}
const http = axios.create(axiosDefaults)
//register interceptor like this
http.interceptors.request.use(
function (config) {
// Do something before request is sent
const token = window.localStorage.getItem('token') //do not store token on localstorage!!!
config.headers.Authorization = token
return config
},
function (error) {
// Do something with request error
return Promise.reject(error)
}
)
Enter fullscreen mode
Exit fullscreen mode
But, in this article, we will use the response interceptor, because is where we want to deal with errors. Nothing stops you to extend the solution to handle request errors as well.
An simple use of response interceptor, is to call ours big ugly function to handle all sort of errors.
As every form of automatic handler, we need a way to bypass this (disable), when we want. We are gonna extend the AxiosRequestConfig interface and add two optional options raw and silent. If raw is set to true, we are gonna do nothing. silent is there to mute notifications that we show when dealing with global errors.
declare module 'axios' {
export interface AxiosRequestConfig {
raw?: boolean
silent?: boolean
}
}
Enter fullscreen mode
Exit fullscreen mode
Next step is to create a Error class that we will throw every time we want to inform the error handler to assume the problem.
export class HttpError extends Error {
constructor(message?: string) {
super(message) // 'Error' breaks prototype chain here
this.name = 'HttpError'
Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain
}
}
Enter fullscreen mode
Exit fullscreen mode
Now, let’s write the interceptors:
// this interceptor is used to handle all success ajax request
// we use this to check if status code is 200 (success), if not, we throw an HttpError
// to our error handler take place.
function responseHandler(response: AxiosResponse<any>) {
const config = response?.config
if (config.raw) {
return response
}
if (response.status == 200) {
const data = response?.data
if (!data) {
throw new HttpError('API Error. No data!')
}
return data
}
throw new HttpError('API Error! Invalid status code!')
}
function responseErrorHandler(response) {
const config = response?.config
if (config.raw) {
return response
}
// the code of this function was written in above section.
return httpErrorHandler(response)
}
//Intercept after response, usually to deal with result data or handle ajax call errors
const axiosDefaults = {}
const http = axios.create(axiosDefaults)
//register interceptor like this
http.interceptors.response.use(responseHandler, responseErrorHandler)
Enter fullscreen mode
Exit fullscreen mode
Well, we do not need to remember our magical badass function in every ajax call we made. And, we can disable when we want, just passing raw to request config.
import axios from 'axios'
// automagically handle error
axios
.get('/users')
.then((response) => {
const userList = response.data
console.log(userList)
})
//.catch(httpErrorHandler) this is not needed anymore
// to disable this automatic error handler, pass raw
axios
.get('/users', {raw: true})
.then((response) => {
const userList = response.data
console.log(userList)
}).catch(() {
console.log("Manually handle error")
})
Enter fullscreen mode
Exit fullscreen mode
Ok, this is a nice solution, but, this bad-ass ugly function will grow so much, that we cannot see the end. The function will become so big, that anyone will want to maintain.
Can we improve more? Oh yeahhh.
The IMPROVED and elegant solution
We are gonna develop an Registry class, using Registry Design Pattern. The class will allow you to register error handling by an key (we will deep dive in this in a moment) and a action, that can be an string (message), an object (that can do some nasty things) or an function, that will be executed when the error matches the key. The registry will have parent that can be placed to allow you override keys to custom handle scenarios.
Here are some types that we will use througth the code:
// this interface is the default response data from ours api
interface HttpData {
code: string
description?: string
status: number
}
// this is all errrors allowed to receive
type THttpError = Error | AxiosError | null
// object that can be passed to our registy
interface ErrorHandlerObject {
after?(error?: THttpError, options?: ErrorHandlerObject): void
before?(error?: THttpError, options?: ErrorHandlerObject): void
message?: string
notify?: QNotifyOptions
}
//signature of error function that can be passed to ours registry
type ErrorHandlerFunction = (error?: THttpError) => ErrorHandlerObject | boolean | undefined
//type that our registry accepts
type ErrorHandler = ErrorHandlerFunction | ErrorHandlerObject | string
//interface for register many handlers once (object where key will be presented as search key for error handling
interface ErrorHandlerMany {
[key: string]: ErrorHandler
}
// type guard to identify that is an ErrorHandlerObject
function isErrorHandlerObject(value: any): value is ErrorHandlerObject {
if (typeof value === 'object') {
return ['message', 'after', 'before', 'notify'].some((k) => k in value)
}
return false
}
Enter fullscreen mode
Exit fullscreen mode
So, with types done, let’s see the class implementation. We are gonna use an Map to store object/keys and a parent, that we will seek if the key is not found in the current class. If parent is null, the search will end. On construction, we can pass an parent,and optionally, an instance of ErrorHandlerMany, to register some handlers.
class ErrorHandlerRegistry {
private handlers = new Map<string, ErrorHandler>()
private parent: ErrorHandlerRegistry | null = null
constructor(parent: ErrorHandlerRegistry = undefined, input?: ErrorHandlerMany) {
if (typeof parent !== 'undefined') this.parent = parent
if (typeof input !== 'undefined') this.registerMany(input)
}
// allow to register an handler
register(key: string, handler: ErrorHandler) {
this.handlers.set(key, handler)
return this
}
// unregister a handler
unregister(key: string) {
this.handlers.delete(key)
return this
}
// search a valid handler by key
find(seek: string): ErrorHandler | undefined {
const handler = this.handlers.get(seek)
if (handler) return handler
return this.parent?.find(seek)
}
// pass an object and register all keys/value pairs as handler.
registerMany(input: ErrorHandlerMany) {
for (const [key, value] of Object.entries(input)) {
this.register(key, value)
}
return this
}
// handle error seeking for key
handleError(
this: ErrorHandlerRegistry,
seek: (string | undefined)[] | string,
error: THttpError
): boolean {
if (Array.isArray(seek)) {
return seek.some((key) => {
if (key !== undefined) return this.handleError(String(key), error)
})
}
const handler = this.find(String(seek))
if (!handler) {
return false
} else if (typeof handler === 'string') {
return this.handleErrorObject(error, { message: handler })
} else if (typeof handler === 'function') {
const result = handler(error)
if (isErrorHandlerObject(result)) return this.handleErrorObject(error, result)
return !!result
} else if (isErrorHandlerObject(handler)) {
return this.handleErrorObject(error, handler)
}
return false
}
// if the error is an ErrorHandlerObject, handle here
handleErrorObject(error: THttpError, options: ErrorHandlerObject = {}) {
options?.before?.(error, options)
showToastError(options.message ?? 'Unknown Error!!', options, 'error')
return true
}
// this is the function that will be registered in interceptor.
resposeErrorHandler(this: ErrorHandlerRegistry, error: THttpError, direct?: boolean) {
if (error === null) throw new Error('Unrecoverrable error!! Error is null!')
if (axios.isAxiosError(error)) {
const response = error?.response
const config = error?.config
const data = response?.data as HttpData
if (!direct && config?.raw) throw error
const seekers = [
data?.code,
error.code,
error?.name,
String(data?.status),
String(response?.status),
]
const result = this.handleError(seekers, error)
if (!result) {
if (data?.code && data?.description) {
return this.handleErrorObject(error, {
message: data?.description,
})
}
}
} else if (error instanceof Error) {
return this.handleError(error.name, error)
}
//if nothings works, throw away
throw error
}
}
// create ours globalHandlers object
const globalHandlers = new ErrorHandlerRegistry()
Enter fullscreen mode
Exit fullscreen mode
Let’s deep dive the resposeErrorHandler code. We choose to use key as an identifier to select the best handler for error. When you look at the code, you see that has an order that key will be searched in the registry. The rule is, search for the most specific to the most generic.
const seekers = [
data?.code, //Our api can send an error code to you personalize the error messsage.
error.code, //The AxiosError has an error code too (ERR_BAD_REQUEST is one).
error?.name, //Error has a name (class name). Example: HttpError, etc..
String(data?.status), //Our api can send an status code as well.
String(response?.status), //respose status code. Both based on Http Status codes.
]
Enter fullscreen mode
Exit fullscreen mode
This is an example of an error sent by API:
{
"code": "email_required",
"description": "An e-mail is required",
"error": true,
"errors": [],
"status": 400
}
Enter fullscreen mode
Exit fullscreen mode
Other example, as well:
{
"code": "no_input_data",
"description": "You doesnt fill input fields!",
"error": true,
"errors": [],
"status": 400
}
Enter fullscreen mode
Exit fullscreen mode
So, as an example, we can now register ours generic error handling:
globalHandlers.registerMany({
//this key is sent by api when login is required
login_required: {
message: 'Login required!',
//the after function will be called when the message hides.
after: () => console.log('redirect user to /login'),
},
no_input_data: 'You must fill form values here!',
//this key is sent by api on login error.
invalid_login: {
message: 'Invalid credentials!',
},
'404': { message: 'API Page Not Found!' },
ERR_FR_TOO_MANY_REDIRECTS: 'Too many redirects.',
})
// you can registre only one:
globalHandlers.register('HttpError', (error) => {
//send email to developer that api return an 500 server internal console.error
return { message: 'Internal server errror! We already notify developers!' }
//when we return an valid ErrorHandlerObject, will be processed as whell.
//this allow we to perform custom behavior like sending email and default one,
//like showing an message to user.
})
Enter fullscreen mode
Exit fullscreen mode
We can register error handler in any place we like, group the most generic in one typescript file, and specific ones inline. You choose. But, to this work, we need to attach to ours http axios instance. This is done like this:
function createHttpInstance() {
const instance = axios.create({})
const responseError = (error: any) => globalHandlers.resposeErrorHandler(error)
instance.interceptors.response.use(responseHandler, responseError)
return instance
}
export const http: AxiosInstance = createHttpInstance()
Enter fullscreen mode
Exit fullscreen mode
Now, we can make ajax requests, and the error handler will work as expected:
import http from '/src/modules/http'
// automagically handle error
http.get('/path/that/dont/exist').then((response) => {
const userList = response.data
console.log(userList)
})
Enter fullscreen mode
Exit fullscreen mode
The code above will show a Notify ballon on the user screen, because will fire the 404 error status code, that we registered before.
Customize for one http call
The solution doesn’t end here. Let’s assume that, in one, only one http request, you want to handle 404 differently, but just 404. For that, we create the dealsWith function below:
export function dealWith(solutions: ErrorHandlerMany, ignoreGlobal?: boolean) {
let global
if (ignoreGlobal === false) global = globalHandlers
const localHandlers = new ErrorHandlerRegistry(global, solutions)
return (error: any) => localHandlers.resposeErrorHandler(error, true)
}
Enter fullscreen mode
Exit fullscreen mode
This function uses the ErrorHandlerRegistry parent to personalize one key, but for all others, use the global handlers (if you wanted that, ignoreGlobal is there to force not).
So, we can write code like this:
import http from '/src/modules/http'
// this call will show the message 'API Page Not Found!'
http.get('/path/that/dont/exist')
// this will show custom message: 'Custom 404 handler for this call only'
// the raw is necessary because we need to turn off the global handler.
http.get('/path/that/dont/exist', { raw: true }).catch(
dealsWith({
404: { message: 'Custom 404 handler for this call only' },
})
)
// we can turn off global, and handle ourselves
// if is not the error we want, let the global error take place.
http
.get('/path/that/dont/exist', { raw: true })
.catch((e) => {
//custom code handling
if (e.name == 'CustomErrorClass') {
console.log('go to somewhere')
} else {
throw e
}
})
.catch(
dealsWith({
404: { message: 'Custom 404 handler for this call only' },
})
)
Enter fullscreen mode
Exit fullscreen mode
The Final Thoughts
All this explanation is nice, but code, ah, the code, is so much better. So, i’ve created an github repository with all code from this article organized to you try out, improve and customize.
- Click here to access the repo in github.
FOOTNOTES:
- This post became so much bigger than a first realize, but i love to share my thoughts.
- If you have some improvement to the code, please let me know in the comments.
- If you see something wrong, please, fix-me!