gpt4 book ai didi

javascript - 使用 navigator.sendBeacon 发送 application/json 数据,preflight 成功但没有 post

转载 作者:搜寻专家 更新时间:2023-11-01 00:05:25 26 4
gpt4 key购买 nike

我在使用 sendBeacon 将数据发布到服务器时遇到问题。

它适用于 chrome(因为 Chrome 似乎跳过预检)但在 Firefox 中,预检(OPTIONS)与请求 header 一起发送:

Host: example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0)
Gecko/20100101 Firefox/53.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://example.com
Connection: keep-alive

来自服务器的响应是 200:

Date: Tue, 23 May 2017 15:53:56 GMT
Content-Type: text/html; charset=utf-8
Set-Cookie: __cfduid=df2864c1da991df4abc28d3e73db7ab8f1495554836;expires=Wed, 23-May-18 15:53:56 GMT; path=/; domain=.medialaben.no;HttpOnly
X-Powered-By: Express
Access-Control-Allow-Origin: *
access-control-allow-credentials: true
access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
access-control-allow-headers: content-type,Authorization,Origin,Connection,Accept
Allow: POST
Server: cloudflare-nginx
cf-ray: 363930e0688e3cfb-CPH
Content-Encoding: gzip
X-Firefox-Spdy: h2

客户端代码:

let inscreenCollection = [someObject, someObject2]
let headers = {
type: "application/json"
};

let blob = new Blob([JSON.stringify(inscreenCollection)], headers);
navigator.sendBeacon(URL, blob);

服务器正在使用来自 npm 的 CORS 包:

const corsOptions = {
optionsSuccessStatus: 200,
credentials: true,
allowedHeaders: 'Content-Type',
preflightContinue: true,
}
app.options('/a/', cors(corsOptions));
app.post('/a/', cors(corsOptions), (req, res) => {
// do stuff
});

编辑:错误消息是 Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’).

有人知道这里可能有什么问题吗?

最佳答案

信标确实 under some circumstances使用凭据发送,因此您需要避免这些情况或避免使用 origin *。

A request initiated by sendBeacon is subject to following properties:

If the payload is one of application/x-www-form-urlencoded, multipart/form-data, or text/plain, then the request is a simple request that does not require an additional CORS-preflight; same as scripted form-post or XHR/fetch.

Otherwise, if the payload is a Blob and the resulting Content-Type is not a simple header, then a CORS preflight is made and the server needs to first allow such requests by returning the appropriate set of CORS headers (Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Access-Control-Allow-Headers); same as XHR/fetch.

关于javascript - 使用 navigator.sendBeacon 发送 application/json 数据,preflight 成功但没有 post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44139967/

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