且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Slack 传入 webhook:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Content-type

更新时间:2022-01-18 21:23:54

不幸的是,Slack API 端点在处理来自前端 JavaScript 代码的跨域请求时似乎被破坏了——因为它不处理 CORS 预检 OPTIONS 请求,因此唯一的解决方案似乎是省略 Content-Type 标头.

That Slack API endpoint unfortunately appears to be broken in its handling of cross-origin requests from frontend JavaScript code—in that it doesn’t handle the CORS preflight OPTIONS request as it should—so the only solution seems to be to omit the Content-Type header.

因此,您似乎需要从请求代码的 headers 部分中删除以下内容:

So it looks like you need to remove the following from the headers part of your request code:

'Content-type': 'application/json'

该部分会触发您的浏览器执行 CORS 预检选项代码>请求.因此,为了让您的浏览器允许您的前端 JavaScript 代码发送您尝试执行的 POST 请求,https://hooks.slack.com/services API端点必须返回一个 Access-Control-Allow-Headers 响应标头,该标头的值中包含 Content-Type.

That part triggers your browser to do a CORS preflight OPTIONS request. So, for your browser to allow your frontend JavaScript code to send the POST request you’re trying to do, the https://hooks.slack.com/services API endpoint must return an Access-Control-Allow-Headers response header that contains Content-Type in its value.

但是那个端点没有返回那个,所以预检失败并且浏览器停在那里.

But that endpoint doesn’t return that, so the preflight fails and the browser stops right there.

通常,当从前端 JavaScript 发布到需要 JSON 的 API 端点时,将 Content-Type: application/json 标头添加到请求中正是您需要做的并且应该做的事情.但在这种情况下并非如此——因为 API 端点没有正确处理它.

Normally when posting from frontend JavaScript to an API endpoint that expects JSON, adding that Content-Type: application/json header to the request is exactly what you need to do and should do. But not in this case—because that API endpoint doesn’t handle it properly.