【发布时间】:2020-03-25 02:25:36
【问题描述】:
我正在构建一个带有 Rails 后端的 Vue 前端。
在前端,我使用的是 Axios,并且设置了这些拦截器进行身份验证:
import axios from 'axios'
const API_URL = 'http://localhost:3000'
const securedAxiosInstance = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
})
const plainAxiosInstance = axios.create({
baseURL: API_URL,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
})
securedAxiosInstance.interceptors.request.use(config => {
const method = config.method.toUpperCase()
if (method !== 'OPTIONS' && method !== 'GET') {
config.headers = {
...config.headers,
'X-CSRF-TOKEN': localStorage.csrf
}
}
return config
})
securedAxiosInstance.interceptors.response.use(null, error => {
if (error.response && error.response.config && error.response.status === 401) {
// If 401 by expired access cookie, we do a refresh request
return plainAxiosInstance.post('/refresh', {}, { headers: { 'X-CSRF-TOKEN': localStorage.csrf } })
.then(response => {
localStorage.csrf = response.data.csrf
localStorage.signedIn = true
// After another successfull refresh - repeat original request
let retryConfig = error.response.config
retryConfig.headers['X-CSRF-TOKEN'] = localStorage.csrf
return plainAxiosInstance.request(retryConfig)
}).catch(error => {
delete localStorage.csrf
delete localStorage.signedIn
// redirect to signin if refresh fails
location.replace('/')
return Promise.reject(error)
})
} else {
return Promise.reject(error)
}
})
export { securedAxiosInstance, plainAxiosInstance }
在 main.js 上,我以这种方式提供它们:
import VueAxios from 'vue-axios'
import { securedAxiosInstance, plainAxiosInstance } from './axios'
Vue.use(VueAxios, {
secured: securedAxiosInstance,
plain: plainAxiosInstance
})
new Vue({
el: '#app',
router,
store,
securedAxiosInstance,
plainAxiosInstance,
render: h => h(App)
})
在组件中我可以成功地使用它们,例如:
this.$http.secured.get('/items')
问题是我无法在我得到的商店中使用它们: 无法读取未定义的“安全”属性”
我在商店里试过:
import { securedAxiosInstance, plainAxiosInstance } from '../axios'
const store = new Vuex.Store({
secured: securedAxiosInstance,
plain: plainAxiosInstance,
.....
正确的做法是什么?
【问题讨论】:
-
你打算如何在商店中使用它们?
-
我在 store 和 modules 中尝试了很多组合,包括我在 main.js 中所做的相同导入。但它们都不起作用。
-
您可以尝试
this._vm.$http.secured.get('/items')或将 vue 实例作为有效负载传递给您的变更/操作 -
是的,修复了它。如果你把它放在一个答案中,我会接受它。你也可以解释一下吗?谢谢!