/axios.js Secret
Last active
July 25, 2023 08:40
frequently used axios code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require('axios') | |
// 1. GET | |
axios.get('https://jsonplaceholder.typicode.com/todos/1') | |
.then (resp => { console.log(resp.data) }) | |
.catch (e => { console.error(e.message) }) | |
// { userId: 1, id: 1, title: 'delectus aut autem', completed: false } | |
// 2. GET with param (params in axios are in fact query string parameters) | |
axios.get('https://jsonplaceholder.typicode.com/todos', { params: {id: 1} }) | |
.then (resp => { console.log(resp.data) }) | |
.catch (e => { console.error(e.message) }) | |
.finally(() => { console.log('finally!') } ) | |
// Note that 'finally!' may be printed first but it's actually executed last. | |
// Perhaps it has something to do with console.log | |
// [ { userId: 1, id: 1, title: 'delectus aut autem', completed: false } ] | |
// 3. async/await | |
async function func () { | |
try { | |
let url = 'https://jsonplaceholder.typicode.com/todos/1' | |
let resp = (await axios.get(url)).data | |
console.log(resp) | |
} catch (e) { | |
console.error(e.message) | |
} | |
} | |
func() | |
// 4. POST | |
axios.post('https://jsonplaceholder.typicode.com/posts', { | |
title: 'foo', | |
body: 'baaar', | |
userId: 1, | |
}).then(function (response) { | |
console.log(response.data) | |
}).catch(function (error) { | |
console.log(error.message) | |
}) | |
// { title: 'foo', body: 'baaar', userId: 1, id: 101 } | |
// 5. Promise.all | |
const getTodo1 = () => axios.get('https://jsonplaceholder.typicode.com/todos/1') | |
const getTodo2 = () => axios.get('https://jsonplaceholder.typicode.com/todos/2') | |
Promise.all([getTodo1(), getTodo2()]).then( results => { | |
console.log(results[0].data) | |
console.log(results[1].data) | |
}) | |
// 6. Axios instance: a promise | |
const a = axios({ | |
method: 'get', | |
url: 'https://jsonplaceholder.typicode.com/todos', | |
params: { | |
id: 1 | |
} | |
}) | |
async function fun () { | |
console.log((await a).data) | |
} | |
fun() | |
// 7. Axios download image/stream | |
const fs = require('fs') | |
axios({ | |
method: 'get', | |
url: 'https://img2.baidu.com/it/u=2441421882,4186445682&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=720', | |
responseType: 'stream' | |
}) | |
.then(function (response) { | |
response.data.pipe(fs.createWriteStream('tom_call.jpg')) | |
}); | |
// 8. Simplest | |
const simp = axios('https://jsonplaceholder.typicode.com/todos/1') | |
async function fun () { | |
console.log((await simp).data) | |
} | |
fun() | |
// 9. Create an instance | |
const instance = axios.create({ | |
baseURL: 'https://jsonplaceholder.typicode.com/', | |
timeout: 3000, | |
headers: {'X-Custom-Header': 'foobar'} | |
}) | |
instance.get('/todos/1') | |
.then(r => { console.log(r.data) }) | |
.catch(e => { console.log(e.message) }) | |
// Available instance methods, the specified config will be merged with the instance config | |
// 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]]) | |
// axios#getUri([config]) | |
// 10. alter instance after created: | |
instance.defaults.headers.common['Authorization'] = 'secret_token' | |
// 11. Global config | |
axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com' | |
axios.defaults.headers.common['Authorization'] = 'secret_token' | |
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' | |
axios.get('/todos/1').then(r => console.log(r.data)).catch(e => console.error(e.message)) | |
// 12. Interceptors | |
// request interceptor | |
axios.interceptors.request.use( config => { | |
// do something before request | |
console.log(config.url) | |
console.log(config.params) | |
return config | |
}, error => { | |
// do something with request error | |
console.log('request error: ', error.message) | |
return Promise.reject(error) | |
}) | |
// response interceptor | |
axios.interceptors.response.use(function (response) { | |
// Any status code that lie within the range of 2xx cause this function to trigger | |
// Do something with response data | |
return response | |
}, function (error) { | |
// Any status codes that falls outside the range of 2xx cause this function to trigger | |
// Do something with response error | |
console.log('resp err: ' + error.message) | |
return Promise.reject(error) | |
}) | |
axios.get('https://notexist', { params: {s: 2} }) | |
.then (resp => { console.log(resp.data) }) | |
.catch (e => { console.error(e.message) }) | |
// 13. Remove injector | |
const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); | |
axios.interceptors.request.eject(myInterceptor); | |
instance.interceptors.request.clear(); // Removes interceptors from requests | |
instance.interceptors.response.clear(); // Removes interceptors from responses | |
// 14. instance interceptor | |
const instance = axios.create(); | |
instance.interceptors.request.use(function () {/*...*/}); | |
// 15. error handling | |
axios.get('http://notexist') | |
.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); | |
}); | |
// 16. Get/Post Wrapper | |
export const getData = (url, params) => new Promise((resolve, reject) => { | |
Axios.get(url, {params}) | |
.then(resp => resolve(resp.data.data)) | |
.catch(e => reject(e)) | |
}) | |
export const postData = (url, data) => new Promise((resolve, reject) => { | |
Axios.post(url, data) | |
.then(resp => resolve(resp.data)) | |
.catch(e => reject(e)) | |
}) | |
vue.prototype.$http = { | |
get: getData, | |
post: postData | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment