Joh*_*ris 5 authentication plugins axios nuxt.js
我希望在我的 Nuxt 项目中使用 $auth,特别是在 axios 插件中。
这是我的代码:
插件/api.js
export default function ({ $axios }, inject) {
const api = $axios.create({
headers: {
common: {
Accept: 'text/plain, */*',
},
},
})
// Set baseURL to something different
api.setBaseURL('http://localhost:4100/')
// Inject to context as $api
inject('api', api)
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试使用 @nuxtjs/auth-next 包中的 $auth 时,问题就出现了。
正如文档中所述:
该模块全局注入 $auth 实例,这意味着您可以使用 this.$auth 在任何地方访问它。对于插件、asyncData、fetch、nuxtServerInit 和 Middleware,您可以从 context.$auth 访问它。
我尝试了以下方法:
这会导致 $auth 未定义
导出默认函数 ({ $axios, $auth }, 注入) {
这个是附近的
export default function ({ $axios, app },ject) { console.log(app) //这个在记录的对象中记录 $auth console.log(app.$auth) // 我不明白为什么,但是这个一个返回未定义
我的主要目标是利用this.$auth.strategy.token.get()它并将其传递给使用 this.$api 发出的每个请求的标头(当然,如果令牌存在的话)
我一直在寻找类似的问题和答案,但没有一个可以帮助我解决这个问题,我可以在每次编写 this.$api 时添加令牌,但这会不必要地增加代码。
预先感谢所有人的时间和帮助。
编辑:
好的,现在我做了一个测试。下一个代码实际上正确地记录了 $auth 对象,似乎需要一些时间才能使其工作,但现在我担心使用 setTimeout 可能会导致错误,因为我无法确切知道 $auth 需要多少时间能得到的。
export default function ({ $axios, app }, inject) {
setTimeout(() => {
console.log('After timeout', app.$auth)
}, 50)
Run Code Online (Sandbox Code Playgroud)
编辑2:
所以现在我做了更多的测试,使用 0 毫秒而不是 50 也可以,所以我现在将使用 0 毫秒的 setTimeout,我希望有人找到更好的解决方案或解释为什么在使用 setTimeout 之前 $auth 不可用,这样我就可以决定如何处理我的代码。
编辑3:
在尝试将我以前的所有代码包装在 setTimeout 中后,我注意到代码失败了,所以这不是解决方案。
Joh*_*ris 10
我已经找到了解决方案,因此我将其发布,以便将来遇到相同问题的每个人都可以解决它。
事实证明我可以使用拦截器轻松解决它。
export default function ({ $axios, app }, inject) {
// At this point app.$auth is undefined. (Unless you use setTimeout but that is not a solution)
//Create axios instance
const api = $axios.create({
headers: {
common: {
Accept: 'application/json', //accept json
},
},
})
// Here is the magic, onRequest is an interceptor, so every request made will go trough this, and then we try to access app.$auth inside it, it is defined
api.onRequest((config) => {
// Here we check if user is logged in
if (app.$auth.loggedIn) {
// If the user is logged in we can now get the token, we get something like `Bearer yourTokenJ9F0JFODJ` but we only need the string without the word **Bearer**, So we split the string using the space as a separator and we access the second position of the array **[1]**
const token = app.$auth.strategy.token.get().split(' ')[1]
api.setToken(token, 'Bearer') // Here we specify the token and now it works!!
}
})
// Set baseURL to something different
api.setBaseURL('http://localhost:4100/')
// Inject to context as $api
inject('api', api)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4769 次 |
| 最近记录: |