我無法Access-Control-Expose-Headers從預檢OPTIONS中獲取在本地開發環境中作業的PUT請求 - 瀏覽器似乎忽略它并且不會將列出的標頭公開給 Javascript 代碼。
下面是一個可以在本地運行的示例站點,并在控制臺中查看它null是輸出而不是my-value從服務器回傳的標頭值。
在/etc/hosts添加兩個域:
127.0.0.1 locala.test
127.0.0.1 localb.test
將下面的 python 程式保存到cors.py,并運行它python cors.py
from http.server import BaseHTTPRequestHandler, HTTPServer
class MyServer(BaseHTTPRequestHandler):
# Serves the website that makes the CORS request
# View on http://locala.test:8080/
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write('''
<html>
<head><title>CORS Example</title></head>
<body>
<p>Web page that makes a CORS request</p>
<script>
fetch('http://localb.test:8080/', {
method: 'PUT'
}).then((response) => {
// Outputs null, when it should output x-my-custom
console.log(response.headers.get('x-my-custom'));
})
</script>
</body>
</html>
'''.encode('utf-8'))
# To be accessed via http://localb.test:8080/
def do_OPTIONS(self):
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "http://locala.test:8080")
self.send_header("Access-Control-Allow-Methods", "PUT")
self.send_header("Access-Control-Expose-Headers", "x-my-custom")
self.end_headers()
# To be accessed via http://localb.test:8080/
def do_PUT(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "http://locala.test:8080")
self.send_header("x-my-custom", 'my-value')
self.end_headers()
webServer = HTTPServer(('127.0.0.1', 8080), MyServer)
print('Running. Press CTRL C to stop.')
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print('Stopped')
然后在瀏覽器的http://locala.test:8080中查看。
uj5u.com熱心網友回復:
標Access-Control-Expose-Headers頭不屬于對預檢請求的回應,而是屬于對關聯的實際請求(即PUT在您的情況下為請求)的回應。在預檢回應中指定該標頭無效。
有關這方面的權威來源,請參閱Fetch 標準的相關部分:
對不是 CORS 預檢請求的 CORS 請求的 HTTP 回應也可以包含以下標頭:
Access-Control-Expose-Headers
(我的重點)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/525329.html
