我正在编写一个 Web map ,并尝试从我有凭据的 Web 资源中获取 JSON。这在通过 JuPyteR 笔记本运行的 Python 中非常有效:
import requests
header = { "Accept": "application/json, text/plain, */*",
"Accept-Language": "de-DE",
"Content-Type": "application/json",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Origin": "https://myCoolServer.azurewebsites.net"}
}
dataJSON = json.dumps({ "username": "XXX",
"password": "XXX"}).encode('utf8')
url = "URL/v1/token"
r = requests.post(url, data=dataJSON, headers=header)
来自 python 的请求给出以下 header :
'User-Agent': 'python-requests/2.19.1',
'Accept-Encoding': 'gzip, deflate',
'Accept': 'application/json, text/plain, */*',
'Connection': 'keep-alive',
'Accept-Language': 'de-DE',
'Content-Type': 'application/json',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Content-Length': '67',
'Origin': 'https://myCoolServer.azurewebsites.net'
现在我尝试在 JavaScript 中重新创建它以获取网络 map 中的数据:
$.ajax ({
method: 'POST',
data: JSON.stringify({ "username": name,
"password": pass}),
headers: {
"Accept": "application/json, text/plain, */*",
"Accept-Language": "de-DE",
"Content-Type": "application/json",
"Pragma": "no-cache",
"Cache-Control": "no-cache"
},
dataType:'json',
url:'URL/v1/token',
error: function() {
alert("Login failed. Check username/password!");
},
success: function(resp) {
token=resp.token;
}
控制台显示预检选项调用的以下 header :
Host: "cool API"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de-DE
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: cache-control,content-type,pragma
Origin: https://myCoolServer.azurewebsites.net
DNT: 1
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
来自服务器的预检选项响应成功(200 响应)。但我没有完成 POST,因为 FF 和 Chrome 中的控制台给了我:
Origin https://myCoolServer.azurewebsites.net not found in Access-Control-Allow-Origin header.
来自服务器的响应 header 给了我:
HTTP/1.1 200 OK
Date: Mon, 19 Nov 2018 08:07:30 GMT
Server: Apache/2.4.18 (Ubuntu)
Cache-Control: no-cache, private
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, PUT, GET, DELETE, OPTIONS
Access-Control-Allow-Headers: cache-control,content-type,pragma
Access-Control-Max-Age: 3600
Access-Control-Allow-Origin: null
Content-Length: 0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
由于整个想法在 Python 中有效,我希望我也可以“模仿”Javascript/Jquery 中的行为。所以我正在寻找您的评论/提示。
注意:当使用 CORS 插件在 Chrome 上运行时,整个事情都可以在 JS 中进行...
最佳答案
Python 不会检查 CORS,而浏览器则会检查 CORS,以避免 XSS 等安全问题,
您需要让服务器使用调用端点的域来响应 header “Access-Control-Allow-Origin”(“https://myCoolServer.azurewebsites.net”?)
如果您希望服务器允许被任何域使用调用:
“访问控制允许来源:*”
(当前为“Access-Control-Allow-Origin:null”)
这是必需的,因为浏览器需要知道该服务器是否期望从该域调用。
关于javascript - JQuery 预检请求 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53370860/