axios - 扩展 Nuxt Auth 插件时 Axios 拦截器不起作用
问题描述
我有一个像这样的 Axios 插件:
export default function ({ $axios, $auth }) {
$axios.interceptors.request.use((req) => {
req.data = {
data: {
// some data
}
}
console.log('auth: ', $auth)
return req
})
$axios.defaults.headers['Content-Type'] = 'application/vnd.api+json'
$axios.defaults.headers.Accept = 'application/vnd.api+json'
}
在我的 nuxt.config 我有:
plugins: [
{ mode: 'client', src: '~/plugins/axios' }
],
当我运行我的请求时,我得到一个auth undefined
.
所以我尝试扩展Nuxt Auth 插件:
auth.js:
export default function ({ $auth }) {
if ($auth.loggedIn) {
console.log('loggin in')
} else {
console.log('not loggin in')
}
}
nuxt.config.js:
plugins: [
// { mode: 'client', src: '~/plugins/axios' }
],
auth: {
plugins: [{ src: '~/plugins/axios', ssr: true }, '~/plugins/auth.js'],
// strategies etc..
}
因此,我评论了 Axios 插件,并将其添加到 auth 部分,如 Nuxt Auth 文档中所示。当我运行请求时,它不会记录整个console.log('auth: ', $auth)
跳过 $axios.interceptors.request.use((req) => {
解决方案
最后,我有机会帮助某人 XD #just-signed-up。这是我用来从 axios 拦截器中访问身份验证的代码
nuxt.config.js
auth: {
plugins: [{ src: '~/plugins/axios.js', ssr: true }, '~/plugins/auth.js']
}
auth.js
export default function ({ $auth }) {
if ($auth.loggedIn) {
return true
} else {
return false
}
}
axios.js
export default function ({ $axios, redirect, $auth }) {
$axios.onRequest(config => {
console.log('Making request to ' + config.url)
})
$axios.onError(error => {
const code = parseInt(error.response && error.response.status)
if (code === 401) {
if ($auth.loggedIn) {
$auth.logout()
}
redirect('/login');
}
if (code === 404) {
redirect('/404')
}
})
}
推荐阅读
- android - 为什么firestore不能在android studio上运行
- python - 对 Panda 数据框中的列求和,其中每个单元格值都是一个列表
- bash - Atom 终端插件找不到命令
- r - 如何在 Rshiny 中通过 dotplot/barlpot 在单元格值悬停时显示数据摘要
- c++ - 将 const char* 添加到 string_view
- laravel - 如何在 carbon PHP API 扩展中将小时转换为秒
- c# - 无需登录名和密码即可登录 api 团队
- c - 当父母和孩子都执行 exec() 时等待孩子
- java - 如何修复:提交响应后无法调用 sendRedirect()
- reactjs - React hooks JSX 渲染无法正常工作