-
-
Save 7iomka/1551acac674f7552a01857ac793a9fa2 to your computer and use it in GitHub Desktop.
Nuxt + axios (service pattern style)
This file contains hidden or 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
// ~/services/axiosClient.js | |
import axios from 'axios'; | |
// If you need transformRequest and/or transformResponse | |
// These default transformers should actually be inside the create function | |
// so they can be overriden but there is an issue why it will not work with axios.create() | |
// Link: https://github.com/axios/axios/issues/430 | |
// | |
// Just make it global especially if you only use your own API | |
axios.defaults.transformRequest[1] = function (data, headers) { | |
return JSON.stringify({ yourNewData }) | |
} | |
export default function create(options) { | |
let defaults = { | |
baseURL: process.env.BASE_URL || http://myDefaultUrl.com, | |
//... more defaults | |
} | |
options = Object.assign({}, defaults, options) | |
return axios.create(options) | |
} | |
// ~/services/StudentService.js | |
import create from './axiosClient' | |
const axios = create({ baseURL: 'http://overrideDefault.com' }) | |
export default { | |
async getAll() { | |
return (await axios.get()).data | |
}, | |
async getById(id) { | |
return (await axios.get(id)).data | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment