gpt4 book ai didi

cors - 浏览器没有为跨源请求设置源头?

转载 作者:行者123 更新时间:2023-12-03 14:39:31 26 4
gpt4 key购买 nike

我有一个简单的index.html文件。此 html 正在从 localhost:3000 加载

<body>
<h1>Some app</h1>
<script src="http://localhost:3005/script.js"></script>
</body>

script.js设置为从另一个来源加载:localhost:3005 .

据我了解,浏览器应该拦截请求并添加 源头 给它 - 并制作一个 预检请求 localhost:3005服务器检查 localhost:3000被允许。

但我没有得到 origin .浏览器似乎没有添加源头。
这是负责为 script.js 提供服务的服务器文件( localhost:3005)。我正在使用 cors module .
const app = express()

const whitelist = ["http://localhost:3001"]
const corsOptions = {
origin: function(origin, callback) {
console.log("origin is: ", origin); //undefined -- why is undefined??

if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
}
else {
callback(new Error('Not allowed by CORS'))
}
}
}

app.use(cors(corsOptions), express.static(__dirname))
app.listen(3005, () => {
console.log("server listening on port 3005")
})

我的实际目标是白名单 仅限 localhost:3000询问我的 script.js
我把 localhost:3001只是为了测试我是否真的得到了一个 cors 错误 - 它应该是。

但我什至没有得到起源 - 是什么原因造成的?
我在 Firefox 和 Chrome 中都得到了相同的行为。我误解了这个孔的过程吗?谢谢 :)

编辑:也许看到请求会有所帮助

browser doesn't attach the origin header

最佳答案

我认为您可能误解了 CORS 的目的。它使服务器能够选择加入某些类型的请求,否则这些请求将在浏览器的同源策略下被禁止。它没有提供一种机制来禁止以前允许的请求。

src 中执行来自外国的脚本的 <script>标签在同源策略下一直是允许的,因此 CORS 根本不适用。这就是请求中没有 header 的原因。

My actual goal is to white-list only localhost:3000 for asking for my script.js.



您不能为此使用 CORS。事实上,你可能根本无法做到这一点。我会退后一步,问你为什么要这样做。如果您尝试保护私有(private)数据,那么可能需要某种身份验证机制( token 、cookie 等)。

关于cors - 浏览器没有为跨源请求设置源头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com