npm install axios
<script src='https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js'></script>
-
import axios
-
axios.get(url)
-
axios.post(url)
-
axios.patch/put(url)
-
axios.delete(url)
-
default get axios(url)
-
returns a promise
-
response data located in data property
-
error in error.response
import axios from 'axios';
const fetchData = async () => {
try {
// axios.get(), axios.post(),axios.put(), axios.delete()
const response = await axios(url);
console.log(response);
} catch (error) {
console.log(error.response);
}
};
-
second argument
-
axios.get(url,{})
-
third argument in requests with data
-
axios.post(url,{data},{})
const fetchDadJoke = async () => {
try {
const { data } = await axios(url, {
headers: {
Accept: 'application/json',
},
});
// console.log(data);
setJoke(data.joke);
} catch (error) {
console.log(error.response);
}
};
- send data to the server
- axios.post(url, { data })
- more options (auth header) - axios.post(url, { data },{})
try {
const resp = await axios.post(url, { data });
} catch (error) {
console.log(error.response.data);
}
// In latest axios version common property returns "undefined"
// axios.defaults.headers.common['Accept'] = 'application/json';
axios.defaults.headers['Accept'] = 'application/json';
axios.defaults.baseURL = 'https://api.example.com';
// In latest axios version common property returns "undefined"
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded';
const authFetch = axios.create({
baseURL: 'https://www.course-api.com',
headers: {
Accept: 'application/json',
},
});
- global and custom
authFetch.interceptors.request.use(
(request) => {
// request.headers.common['Accept'] = `application/json`;
request.headers['Accept'] = `application/json`;
console.log('request sent');
// must return request
return request;
},
(error) => {
return Promise.reject(error);
}
);
authFetch.interceptors.response.use(
(response) => {
console.log('got response');
return response;
},
(error) => {
console.log(error.response);
if (error.response.status === 404) {
// do something
console.log('NOT FOUND');
}
return Promise.reject(error);
}
);
In the latest version there is no common property
// In latest axios version common property returns "undefined"
// axios.defaults.headers.common['Accept'] = 'application/json';
axios.defaults.headers['Accept'] = 'application/json';
// In latest axios version common property returns "undefined"
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers['Authorization'] = AUTH_TOKEN;
// request.headers.common['Accept'] = `application/json`;
request.headers['Accept'] = `application/json`;