同源策略,浏览器忽略不同的端口? [关闭]

问题描述 投票:0回答:0

我想看看如果不在我的后端服务器(Django Rest Framework)上设置与同源策略相关的 CORS 标头,Web 浏览器会如何运行。从this文档同源策略应该查看协议端口和主机,但是我可以从运行在以下位置的后端服务器读取响应:

http://127.0.0.1:8000/
来自我在
http://127.0.0.1:5500/index.html
(Visual Studio Code-实时服务器,请注意不同的端口号),这是请求:

const button1 = document.getElementById("button1");
button1.addEventListener("click", () => {
  fetch("http://127.0.0.1:8000/api/users/")
    .then((response) => {
      return response.json();
    })
    .then((data) => console.log(data));
});

现在,如果我将我的网址从

http://127.0.0.1:5500/index.html
更改为
http://localhost:5500/index.html
并发出请求,我将收到预期的消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/api/users/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

那么为什么浏览器不关心同源策略中提到的不同端口号?

编辑:

我的 Firefox 似乎有问题,因为在这两种情况下它都被 Chromium 阻止了 (localhost/127.0.0.1)。为了可读性,我用 FastAPI/Uvicorn 创建了一个不同的服务器(更少的标头,而且我没有设置 CORS 标头)这里是请求/响应:

未阻塞:

Status
200
OK
VersionHTTP/1.1
Transferred150 B (25 B size)
Referrer Policystrict-origin-when-cross-origin
Request PriorityHighest  
....
Response
HTTP/1.1 200 OK
date: Thu, 23 Mar 2023 09:15:41 GMT
server: uvicorn
content-length: 25
content-type: application/json
....
Request
GET / HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/111.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://127.0.0.1:5500/
Origin: http://127.0.0.1:5500
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site

阻塞:

Status
200
OK
VersionHTTP/1.1
Transferred150 B (25 B size)
Referrer Policystrict-origin-when-cross-origin
Request PriorityHighest
....
Response
HTTP/1.1 200 OK
date: Thu, 23 Mar 2023 09:18:22 GMT
server: uvicorn
content-length: 25
content-type: application/json
....
Request
GET / HTTP/1.1
Host: 127.0.0.1:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/111.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:5500/
Origin: http://localhost:5500
Connection: keep-alive
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
http web browser cors same-origin-policy
© www.soinside.com 2019 - 2024. All rights reserved.