首先,在我打开这个问题之前,我搜索了很多,无法找到我正在寻找的解决方案。这就是为什么新的问题。
在我提出问题之前,您需要了解以下几点。
所以这是我的问题,我需要在GET和POST中添加JWT令牌。我在请求标题中添加了JWT,使用了两种方法" AJAX标题"和" AJAX Beforesend "。
下面是我尝试使用 AJAX标题
尝试的snippit$.ajax({
url: serverUrl,
type: "GET",
dataType: 'json',
headers: {
'Authorization': 'JWT xxxxxxxxx'
},
success: function(response) {
console.log(response);
},
error: function(xhr, err) {
console.log(xhr.readyState, "Readystate Error");
console.log(xhr.status, "Error Status");
console.log(xhr.responseText, "Error Response Text");
},
complete: function(xhr, status) {
console.log(xhr.status, "server status code");
}
});
这是我尝试使用 AJAX BeforeSend
发送的snippit$.ajax({
url: serverUrl,
type: "GET",
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization','JWT xxxxxx');
},
success: function(response) {
console.log(response);
},
error: function(xhr, err) {
console.log(xhr.readyState, "Readystate Error");
console.log(xhr.status, "Error Status");
console.log(xhr.responseText, "Error Response Text");
},
complete: function(xhr, status) {
console.log(xhr.status, "server status code");
}
});
对于这两个函数,这是发送到服务器并得到响应的内容。 (使用 WireShark 进行捕获)
OPTIONS /somepage/ HTTP/1.1
Host: *(serverURL)*
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://evil.com/
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Referer: http://localhost/app/page1.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,ca;q=0.6
HTTP/1.0 403 Forbidden
Date: Thu, 05 Jan 2017 06:58:16 GMT
Server: WSGIServer/0.1 Python/2.7.6
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Allow: GET, POST, OPTIONS
{"detail":"Authentication credentials were not provided."}
这是控制台日志
XMLHttpRequest cannot load "serverurl"/somepage/. Response for preflight has invalid HTTP status code 403
那我在这里做错了什么?终端和Web Gui都在工作,但不适用于我的应用程序。我该怎么办?我需要在请求头中添加JWT令牌,以便我可以从服务器获取数据。