Answer the question
In order to leave comments, you need to log in
How to overcome the Cannot read property '$root' of undefined error in the this.$root.$emit construct?
At the root of the project, there is a client.js file, where any request to the API is constructed using axios.
import axios from 'axios'
import { api_config } from '../../api_config'
import { getApiToken } from '../../api_config'
import router from '../../src/router/index'
function request(method, url, params, data) {
let axios_config = {
// `baseURL` is the server URL that will be used for the request
baseURL: api_config.api_url,
// `method` is the request method to be used when making the request
method: method,
// `url` will be prepended to `baseURL` unless `baseURL` is absolute.
url: url,
headers: {
Authorization: 'Bearer ' + getApiToken()
}
}
if (params) {
// `params` are the URL parameters to be sent with the request
axios_config.params = params
}
if (data) {
// `data` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
axios_config.data = data
}
// intercept responses before they are handled by then or catch
axios.interceptors.response.use((response) => {
return response
}, (error) => {
if (error.response.status == 401) {
localStorage.removeItem('token')
router.push({ path: '/login' })
}
if (error.response.status == 403) {
this.$root.$emit('modal', true)
}
return Promise.reject(error)
})
return axios(axios_config)
}
function get(url) {
return request('get', url, null, null)
}
function post(url, data) {
data = data || {}
return request('post', url, null, data)
}
function put(url, data) {
data = data || {}
return request('put', url, null, data)
}
function remove(url) {
return request('delete', url, null, null)
}
export default {get, post, put, remove, request}
axios.interceptors.response.use
to catch errors. this.$root.$emit
because now I'm getting an errorCannot read property '$root' of undefined
at __WEBPACK_IMPORTED_MODULE_0_axios___default.a.interceptors.response.use
Answer the question
In order to leave comments, you need to log in
You should not use this construct in this file, because as a matter of fact at you it is the client for work on a network. Return data from the client to the component and perform the necessary actions in it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question