首页 > 解决方案 > fetch() with 'credentials: true' 在 Chrome 中的 Tampermonkey 用户脚本中失败

问题描述

即使 CORS 配置正确,在 Chrome 中的 Tampermonkey 用户脚本中Cookie发送credentials: true-请求时, -header 也会丢失。fetch问题是什么?

附加信息:

相同的代码在 Firefox 的 Tampermonkey 用户脚本中按预期工作。

我在跨域服务器上有一个 API 端点,该端点已正确配置为接受fetch带有credentials: true.

这是我当前的代码:

fetch('https://example.com/api/my/endpoint', {
    credentials: 'include',
    headers: {
        'Content-Type': 'application/json'
    }
});

-preflight OPTIONS-requestexample.com成功进行并返回以下标头:

access-control-allow-origin: https://requestingsite.com
allow: GET, OPTIONS
access-control-allow-methods: GET, OPTIONS
access-control-allow-headers: Origin, X-Requested-With, Content-Type, Accept, Cookie, Authorization, Pragma
access-control-allow-credentials: true

之后,发出GET-request to example.com。它在 Firefox 中按预期工作 - 它Cookie在请求中发送必要的 -header。

不过,它在 Chrome 中不起作用。Chrome 中的请求包含必要的Origin-header 并匹配access-control-allow-origin服务器返回的 header 内的内容。

标签: corsfetchtampermonkeyuserscripts

解决方案


推荐阅读