简体   繁体   中英

Global API call Vue.js

I'm having trouble creating a global variable that contains API. I need to use this variable throughout my app, so it will be easier to change API link when the time comes. How can I do that? So far I've done the following:

Created a file called config.js

const baseURL = 'http://myapi'

export default {
    baseURL
}

I'm using Vuex to make api calls so the part where I try to receive data looks like this in my store:

import baseURL from '../../../config.js'

    async fetchStaff({ commit }, id, baseURL) {
    if (id === undefined) {
        const response = await axios.get(baseURL + `/employee/staff`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
        // eslint-disable-next-line no-console
        console.log(response.data)
    } else {
        const response = await axios.get(baseURL + `/employee/${id}`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
    }
},

baseURL is undefind in store. Can someone point out the mistake here, please?

config.js

// Bases
export const baseURL = 'http://myapi'

// Endpoints
export const api_1 = '/api1'
export const api_2 = param1 => `/api2/ + ${param1}`

store.js

// import apis you want to use this file.
import { baseURL, api_1 } from '../../../config.js'

First, you're exporting an object in your config.js. so if you import it like below:

import baseURL from '../../../config.js'

Then you will get the whole object of configs. Instead, you could import the baseURL variable by doing this:

import { baseURL } from '../../../config.js'

Second, in this line:

async fetchStaff({ commit }, id, baseURL )

baseURL is recognized as a parameter. that's why it always has no value or undefined , I would recommend removing it from the function parameter. So it will probably look like below:

import { baseURL } from '../../../config.js'


async fetchStaff({ commit }, id) {
    if (id === undefined) {
        const response = await axios.get(baseURL + `/employee/staff`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
        // eslint-disable-next-line no-console
        console.log(response.data)
    } else {
        const response = await axios.get(baseURL + `/employee/${id}`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
    }
},

thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM