问题描述:
在使用VueJS和Django开发应用程序时,遇到了Axios授权无法工作的问题。无论如何设置授权头,都无法成功进行身份验证。
解决方法:
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = True
import axios from 'axios';
const token = localStorage.getItem('token');
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
created() {
const token = localStorage.getItem('token');
if (!token) {
// 重定向到登录页面或提示用户进行身份验证
this.$router.push('/login');
}
}
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.AllowAllUsersModelBackend',
'django.contrib.auth.backends.RemoteUserBackend',
'django.contrib.auth.backends.ModelBackend',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
]
from django.urls import include, path
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
...
path('api/auth/token/', obtain_jwt_token),
...
]
这些解决方法应该可以解决Axios授权无法工作的问题。根据您的具体情况,可能需要进行一些调整和修改。
上一篇:axios使用数据服务器参数
下一篇:Axios刷新令牌问题