Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么在访问API时需要在请求头中添加“Authorization”?_Javascript_Python_Django Allauth_Django Rest Auth - Fatal编程技术网

Javascript 为什么在访问API时需要在请求头中添加“Authorization”?

Javascript 为什么在访问API时需要在请求头中添加“Authorization”?,javascript,python,django-allauth,django-rest-auth,Javascript,Python,Django Allauth,Django Rest Auth,我使用Python/Django编写后端,使用Django Rest框架编写API,我还使用了Rest\u auth,allauth,请参见我的settings.py: INSTALLED_APPS = [ ... 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', # API docs 'rest_auth', 'a

我使用Python/Django编写后端,使用Django Rest框架编写API,我还使用了
Rest\u auth
allauth
,请参见我的
settings.py

INSTALLED_APPS = [
    ...

    'corsheaders', 

    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_docs',  # API docs
    'rest_auth',
    'allauth',
    'allauth.account',
但是当前端访问API时,它必须在 请求标头,否则无法访问成功: 例如:

    var that = this

    // login 
    that.$http.post(Urls.users.login(), params).then((response) => {

      that.$Cookies.set('token', response.data.key);

    }).catch((response) => {   //  if the header do not have `Authorization`, there will go to there directly, and pay attention: the response is undefined.


      }
    )

您将
'rest\u framework.authtoken'
添加到
已安装的应用程序中
并设置

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}
在settings.py中。 然后,当您使用不安全的方法(如
post\patch\delete
)询问服务器时,
DjangoRestFramework
将检查您的身份。您的
login
方法由
post
方法处理,该方法将询问身份。但您在
登录后获得
令牌

有两种方法可以解决您的问题,一种是:

'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.AllowAny',
),
不建议这样做。第二种方法是为您的
登录设置权限,如:

from rest_framework.permissions import AllowAny
@list_route(methods=['POST'], permission_classes=[AllowAny])
def login(self, request):
    pass

rest\u auth
是否是
rest\u框架的一部分(django rest框架的一部分)?否,它是第三方应用程序。