Используем axios для доступа к api
Содержание:
- Axios GET request with callbacks
- Notes
- Example
- Consuming The RESTful API Using Axios
- Base Example
- Using application/x-www-form-urlencoded format
- Config Defaults
- Handling Errors
- Example
- Cancellation
- Зачем нужна выделенная Frontend Core команда и как мы внедряли дизайн систему
- axios API
- API
- Example
- Использование формата application/x-www-form-urlencoded
- Handling Errors
- axios API
- Handling Errors
- Interceptors
- Vue and Axios GET Example
- Manual Requests
- axios-observable API
- Организация типовых модулей во Vuex
- Как эффективно применять React Context
- Отмена запроса
- Handling Errors
Axios GET request with callbacks
In the first example, we create a simple GET request. We use callbacks.
simple_get.js
const axios = require('axios'); axios.get('http://webcode.me').then(resp => { console.log(resp.data); });
We generate a simple GET request and show the output.
const axios = require('axios');
The Axios library is included.
axios.get('http://webcode.me').then(resp => { console.log(resp.data); });
With , we send a GET request. We output the data
from the response. The data is HTML code.
$node simple_get.js <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>My html page</title> </head> <body> <p> Today is a beautiful day. We go swimming and fishing. </p> <p> Hello there. How are you? </p> </body> </html>
This is the output.
Notes
- It’s possible to use both method and passing a config as a first argument to the hook in a single component. Keep in mind that using method does not make a component re-render the second time while passing a new config as argument does trigger a second render.
- If you use both methods simultaneously ( and passing a config) you might bump into something like this:
const Component = () => { const config, setConfig = React.useState( 'https://api.github.com/users/octocat' ); const { update } = useAxiosRequest(config); // If you click on 'Use update button', a new request is sent. // Then if you lick on 'Use setConfig', nothing happens // because literally nothing has changed - you've updated local state // to the same value as it was before. useAxiosRequest hook remembers // last passed config as an argument and dispatches a new request only // if it actually changes. return ( <div> <button onChange={() => update('https://api.github.com/users/Turanchoks')} > Use update </button> <button onChange={() => setConfig('https://api.github.com/users/octocat')} > Use setConfig </button> </div> ); };
If you use polling, it’s likely that you don’t want to show spinner whenever a polling request occurs. You can use requestId property which equals 1 on the very first request. So isFetching && requestId === 1 is true when it’s a initial request.
Example
Performing a request
import Axios from 'axios-observable'; // or const Axios = require('axios-observable').Axios; // Make a request for a user with a given ID Axios.get('/user?ID=12345') .subscribe( response => console.log(response), error => console.log(error) ); // Optionally the request above could also be done as Axios.get('/user?ID=12345'), { params: { ID: 12345 } }) .subscribe( response => console.log(response), error => console.log(error) );
Performing a request
Axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .subscribe( response => console.log(response), error => console.log(error) );
Consuming The RESTful API Using Axios
After installing Axios, we’ll use it to consume to RESTful API exposed from .
To encapsulate all the code interfacing with REST API server we’ll create a JavaScript class inside the project and we’ll add different methods to send API calls such as POST, GET, PUT and DELETE.
Go ahead and create inside the folder:
Next open using your favorite code editor and add the following code to create the APIService class:
We’ve imported axios, defined an API_URL variable which holds the address of the REST API server and then declared and exported the APIService class with a constructor.
We have different REST endpoints such as and etc. Let’s see an example with the endpoint:
Base Example
There are many times when building application for the web that you may want to consume and display data from an API. There are several ways to do so, but a very popular approach is to use axios, a promise-based HTTP client.
In this exercise, we’ll use the CoinDesk API to walk through displaying Bitcoin prices, updated every minute. First, we’d install axios with either npm/yarn or through a CDN link.
There are a number of ways we can request information from the API, but it’s nice to first find out what the shape of the data looks like, in order to know what to display. In order to do so, we’ll make a call to the API endpoint and output it so we can see it. We can see in the CoinDesk API documentation, that this call will be made to . So first, we’ll create a data property that will eventually house our information, and we’ll retrieve the data and assign it using the lifecycle hook:
new Vue({ el: '#app', data () { return { info: null } }, mounted () { axios .get('https://api.coindesk.com/v1/bpi/currentprice.json') .then(response => (this.info = response)) }}) |
<div id="app"> ` info `</div> |
And what we get is this:
See the Pen First Step Axios and Vue by Vue (@Vue) on CodePen.
Excellent! We’ve got some data. But it looks pretty messy right now so let’s display it properly and add some error handling in case things aren’t working as expected or it takes longer than we thought to get the information.
Using application/x-www-form-urlencoded format
By default, axios serializes JavaScript objects to . To send data in the format instead, you can use one of the following options.
Browser
const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);
Alternatively, you can encode data using the library:
const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 }));
Or in another way (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);
Query string
const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
const url = require('url'); const params = new url.URLSearchParams({ foo: 'bar' }); axios.post('http://something.com/', params.toString());
You can also use the library.
NOTE
The library is preferable if you need to stringify nested objects, as the method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).
Form data
In node.js, you can use the library as follows:
const FormData = require('form-data'); const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_file', fs.createReadStream('/foo/bar.jpg')); axios.post('https://example.com', form, { headers: form.getHeaders() })
Alternatively, use an interceptor:
axios.interceptors.request.use(config => { if (config.data instanceof FormData) { Object.assign(config.headers, config.data.getHeaders()); } return config; });
Config Defaults
You can specify config defaults that will be applied to every request.
Global axios defaults
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';
Custom instance defaults
// Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common'Authorization' = AUTH_TOKEN;
Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in , then property of the instance, and finally argument for the request. The latter will take precedence over the former. Here’s an example.
// Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 });
Handling Errors
axios.get('/user/12345').catch(function(error){if(error.response){console.log(error.response.data);console.log(error.response.status);console.log(error.response.headers);}elseif(error.request){console.log(error.request);}else{console.log('Error',error.message);}console.log(error.config);});
Using the config option, you can define HTTP code(s) that should throw an error.
axios.get('/user/12345',{validateStatusfunction(status){return status <500;}})
Using you get an object with more information about the HTTP error.
axios.get('/user/12345').catch(function(error){console.log(error.toJSON());});
Example
import axios from 'axios' import moxios from 'moxios' import sinon from 'sinon' import { equal } from 'assert' describe('mocking axios requests', function () { describe('across entire suite', function () { beforeEach(function () { // import and pass your custom axios instance to this method moxios.install() }) afterEach(function () { // import and pass your custom axios instance to this method moxios.uninstall() }) it('specify response for a specific request', function (done) { let input = document.querySelector('.UserList__Filter__Input') let button = document.querySelector('.UserList__Filter__Button') input.value = 'flintstone' button.click() // Elsewhere in your code axios.get('/users/search', { params: { q: 'flintstone' } }) is called moxios.wait(function () { let request = moxios.requests.mostRecent() request.respondWith({ status: 200, response: { id: 1, firstName: 'Fred', lastName: 'Flintstone' }, { id: 2, firstName: 'Wilma', lastName: 'Flintstone' } }) .then(function () { let list = document.querySelector('.UserList__Data') equal(list.rows.length, 2) equal(list.rows.cells.innerHTML, 'Fred') equal(list.rows1.cells.innerHTML, 'Wilma') done() }) }) }) it('stub response for any matching request URL', function (done) { // Match against an exact URL value moxios.stubRequest('/say/hello', { status: 200, responseText: 'hello' }) // Alternatively URL can be a RegExp moxios.stubRequest(/say.*/, {/* … */}) let onFulfilled = sinon.spy() axios.get('/say/hello').then(onFulfilled) moxios.wait(function () { equal(onFulfilled.getCall().args.data, 'hello') done() }) }) }) it('just for a single spec', function (done) { moxios.withMock(function () { let onFulfilled = sinon.spy() axios.get('/users/12345').then(onFulfilled) moxios.wait(function () { let request = moxios.requests.mostRecent() request.respondWith({ status: 200, response: { id: 12345, firstName: 'Fred', lastName: 'Flintstone' } }) .then(function () { equal(onFulfilled.called, true) done() }) }) }) }) it('Should reject the request', function (done) { const errorResp = { status: 400, response: { message: 'invalid data' } } moxios.wait(function () { let request = moxios.requests.mostRecent() request.reject(errorResp) }) .catch(function (err) { equal(err.status, errorResp.status) equal(err.response.message, errorResp.response.message) done() }) }) })
Cancellation
You can cancel a request using a cancel token.
You can create a cancel token using the factory as shown below:
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 { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the constructor:
const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel();
Зачем нужна выделенная Frontend Core команда и как мы внедряли дизайн систему
Всем привет, меня зовут Ростислав, я занимаю должность Front Lead в компании ДомКлик. Хочу поделиться с вами опытом создания Web Core команды и сразу ответить на следующие вопросы:
После года существования команды Web Core, у всех сложилось понимание, что в больших компаниях это необходимо, а в стартапах — не обязательно.
Безусловно. Изначально было сложно измерить и спрогнозировать выгоду от её создания, все расчеты, P&L были на словах, в цифрах — только примерные предположения. Спустя год мы можем посчитать сэкономленное время, профиты, и все расчеты говорят о том, что это было не зря.
Если у вас одна цель — создать дизайн систему и выпустить библиотеку компонентов под ключ, то возможно. Если же вы хотите это всё динамически развивать и расширять зоны ответственности команды, то это точно надолго.
Основное направление — дизайн система, но по ходу её разработки у нас появилось еще много интересных задач.
axios API
Requests can be made by passing the relevant config to .
axios(config)
// Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
// GET request for remote image axios({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }) .then(function(response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) });
axios(url)
// Send a GET request (default method) axios('/user/12345');
Request method aliases
For convenience aliases have been provided for all supported request methods.
axios.patch(url])
NOTE
When using the alias methods , , and properties don’t need to be specified in config.
Helper functions for dealing with concurrent requests.
Creating an instance
You can create a new instance of axios with a custom config.
axios.create()
var instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.
API
The package exports one default export and named exports:
useAxios(url|config, options)
The main React hook to execute HTTP requests.
- — The request URL or object, the same argument accepted by .
-
— An options object.
- ( ) — If true, the request is not executed immediately. Useful for non-GET requests that should not be executed when the component renders. Use the function returned when invoking the hook to execute the request manually.
- ( ) — Allows caching to be enabled/disabled for the hook. It doesn’t affect the function returned by the hook.
Returns
-
— The data property (for convenient access).
-
— True if the request is in progress, otherwise False.
-
— The value
-
— The whole object.
-
— A function to execute the request manually, bypassing the cache by default.
- — Same object as , which is shallow-merged with the config object provided when invoking the hook. Useful to provide arguments to non-GET requests.
- — An options object.
Returns
A promise containing the response. If the request is unsuccessful, an exception is thrown and must be handled manually.
Allows to provide custom instances of cache and axios.
- An instance of lru-cache, or to disable the cache
- An instance of
serializeCache()
Dumps the request-response cache, to use in server side rendering scenarios.
Returns
A serializable representation of the request-response cache ready to be used by
loadCache(cache)
Populates the cache with serialized data generated by .
cache The serializable representation of the request-response cache generated by serializeCache
makeUseAxios({ cache, axios })
Creates an instance of the hook configured with the supplied cache and axios instance.
- An instance of lru-cache, or to disable the cache
- An instance of
Returns
An instance of React Hook which will always use the provided cache and axios instance.
The returned value, besides being a function that can be used as a React Hook, also contains the properties:
which are the same as the package’s named exports but limited to the instance returned by .
Example
Performing a request
// Make a request for a user with a given ID axios.jsonp('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // Optionally the request above could also be done as axios.jsonp('/user', { timeout: 1000, params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Performing a request
// Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Performing a request
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Performing multiple concurrent requests
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) { // Both requests are now complete }));
Использование формата application/x-www-form-urlencoded
По умолчанию axios переводит объекты JavaScript в . Чтобы отправить данные в формате , Вы можете использовать один из следующих вариантов.
Браузер
const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);
Кроме того, вы можете декодировать данные, используя библиотеку :
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
const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
Вы также можете использовать библиотеку .
Handling Errors
axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx 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 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });
Using the config option, you can define HTTP code(s) that should throw an error.
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Resolve only if the status code is less than 500 } })
Using you get an object with more information about the HTTP error.
axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); });
axios API
Requests can be made by passing the relevant config to .
axios(config)
// Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
// GET request for remote image in node.js axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) });
axios(url)
// Send a GET request (default method) axios('/user/12345');
Request method aliases
For convenience aliases have been provided for all supported request methods.
axios.patch(url])
NOTE
When using the alias methods , , and properties don’t need to be specified in config.
Concurrency (Deprecated)
Please use to replace the below functions.
Helper functions for dealing with concurrent requests.
axios.all(iterable)
axios.spread(callback)
Creating an instance
You can create a new instance of axios with a custom config.
axios.create()
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.
Handling Errors
axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx 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 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });
Using the config option, you can define HTTP code(s) that should throw an error.
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Resolve only if the status code is less than 500 } })
Using you get an object with more information about the HTTP error.
axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); });
Interceptors
You can intercept requests or responses before they are handled by or .
// Add a request interceptor 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); });
If you may need to remove an interceptor later you can.
var myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
You can add interceptors to a custom instance of axios.
var instance = axios.create(); instance.interceptors.request.use(function () {/*...*/});
Vue and Axios GET Example
Let’s start by getting the list of contacts using an HTTP GET request. Add the following code to the :
We declared a getContacts() method which makes a GET call, using the axios.get() method, to the endpoint. We are taking the data part from the response and then returning a Promise, from the function, which would resolve to an array of contacts or an error.
We also need a method to get single contacts by id or primary key. Let’s add a second method to :
In the same way, the method returns a Promise which would resolve to a single contact or error.
Example Using Http GET Calls
After adding the two methods for sending GET requests to the API server, we can now call them from any Vue component.
First create a Vue components for displaying contacts. Navigate inside then run the following command:
Open the file and start by adding a template:
We use the v-for directive to loop through the contacts array and display information about each contact in a HTML table.
Next, in the same file add the following JavaScript code:
We first declare a contacts and numberOfContacts variables in the data() method of our Vue component. Next, we add a getContacts() method which call the getContacts() of the APIService instance we created in the start of the file. When the promise resolves we assign the results to our declared variables i.e contacts and numberOfContacts. In the mounted() method of the component we call the getContacts() method so we can get contacts to display as soon as the component is mounted.
Manual Requests
On the client, requests are executed when the component renders using a React hook.
This may be undesirable, as in the case of non-GET requests. By using the option you can skip the automatic execution of requests and use the return value of the hook to execute them manually, optionally providing configuration overrides to .
Example
In the example below we use the hook twice. Once to load the data when the component renders, and once to submit data updates via a request configured via the option.
import useAxios from 'axios-hooks' function App() { const { data: getData, : getLoading, error: getError } = useAxios( 'https://reqres.in/api/users/1' ) const { data: putData, : putLoading, error: putError }, executePut = useAxios( { url: 'https://reqres.in/api/users/1', method: 'PUT' }, { manual: true } ) function updateData() { executePut({ data: { ...getData, updatedAt: new Date().toISOString() } }) } if (getLoading || putLoading) return <p>Loading...</p> if (getError || putError) return <p>Error!</p> return ( <div> <button onClick={updateData}>update data</button> <pre>{JSON.stringify(putData || getData, null, 2)}</pre> </div> ) }
axios-observable API
Yeah! We use the exact same config object as axios.
The example below is wrong!
// Send a POST request Axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
use Axios.request(config) instead
// Send a POST request Axios.request({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
// GET request for remote image Axios.request({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }) .subscribe(response => { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) });
Request method aliases
For convenience aliases have been provided for all supported request methods.
Axios.patch(url])
NOTE
When using the alias methods , , and properties don’t need to be specified in config.
Creating an instance
You can create a new instance of Axios with a custom config.
Axios.create()
const instance = Axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.
Организация типовых модулей во Vuex
Vuex — это официальная библиотека для управления состоянием приложений, разработанная специально для фреймворка Vue.js.
Vuex реализует паттерн управления состоянием, который служит централизованным хранилищем данных для всех компонентов приложения.
По мере роста приложения такое хранилище разрастается и данные приложения оказываются помещены в один большой объект.
Работая над проектом CloudBlue Connect и создавая очередной модуль, мы поймали себя на мысли, что пишем один и тот же шаблонный код снова и снова, меняя лишь эндпоинт:
- Репозиторий, в которой содержится логика взаимодействия с бекендом;
- Модуль для Vuex, который работает с репозиторием;
- Юнит-тесты для репозиториев и модулей.
Кроме того, мы отображаем данные в одном списке или табличном представлении с одинаковыми механизмами сортировки и фильтрации. И мы используем практически одинаковую логику извлечения данных, но с разными эндпоинтами.
В нашем проекте мы любим вкладываться в написание переиспользуемого кода. Помимо того, что это в перспективе снижает время на разработку, это уменьшает количество возможных багов в коде.
Для этого мы создали фабрику типовых модулей Vuex, сократившую практически до нуля написание нового кода для взаимодействия с бекендом и хранилищем (стором).
Как эффективно применять React Context
Перевод
В статье Как управлять состоянием React приложения без сторонних библиотек, я писал о том как сочетание локального состояния и контекста (React Context) поможет вам упростить управление состоянием при разработке приложения. В этой статье я продолжу эту тему — мы поговорим о методах эффективного использования потребителей контекста (Context Consumer), которые помогут вам избежать ошибок и упростят разработку приложений и/или библиотек.
Рекомендую перед прочтением этой статьи прочитать Как управлять состоянием React приложения без сторонних библиотек
Особенно обратите внимание на рекомендацию о том что не нужно применять контексты для решения всех проблем связанных с передачей состояния. Однако, когда вам все таки понадобиться применять контексты, надеюсь эта статья поможет вам делать это наиболее эффективным образом
Так же помните о том что контексты НЕ обязательно должны быть глобальными, контекст может (и скорее всего, должен) быть частью какой либо ветки в структуре вашего приложения.
Давайте, для начала, создадим файл src/count-context.js и пропишем там наш контекст:
Отмена запроса
Вы можете отменить запрос, используя cancel token.
Вы можете создать token отмены с помощью фабричной функции , как показано ниже:
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 для отмены запроса, передав функцию конструктору :
const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // исполняемая функция получает функцию отмены в качестве параметра cancel = c; }) }); // отмена запроса cancel();
Handling Errors
axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx 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 // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });
Using the config option, you can define HTTP code(s) that should throw an error.
axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Resolve only if the status code is less than 500 } })
Using you get an object with more information about the HTTP error.
axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); });