How to avoid code duplication when running NUXT.js and Axios?

后端 未结 3 1395
悲哀的现实
悲哀的现实 2021-01-22 10:25

If similar code (as in the example) is duplicated in different components but with slight differences in the name of what I pass in the function parameters

What a

3条回答
  •  面向向阳花
    2021-01-22 10:46

    I used nuxt/axios.js for my nuxt app. You can use it as a plugin.

    In plugins folder, make a file axios.js

    import axios from 'axios'
    
    export default axios.create({
       baseURL: process.env.baseURL,
    })
    

    NOTE: I am storing the base url of the server to be called for APIs in environment variables using dotenv lib. And this way, the base url is set for all the calls to be made.

    Then import it in nuxt.config.js file:

    module.exports = {
    ....
    {
      modules: [
        '@nuxtjs/axios'
      ],
    
      axios: {
      ...
      },
    }
    

    TIP: If you have to store a value in axios like "token" or "cookie" globally. Then you can use axios defaults method

    axios.defaults.headers.common = { Authorization: `bearer ${token}` };
    

提交回复
热议问题