我尝试在浏览器中通过 fetch API 发布 slack 消息:
fetch('https://hooks.slack.com/services/xxx/xxx/xx', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-type': 'application/json'
},
body: JSON.stringify({text: 'Hi there'})
})
.then(response => console.log)
.catch(error => console.error);
};
我收到以下错误消息:
Fetch API cannot load:
https://hooks.slack.com/services/xxxxxxx/xxxxx.
Request header field Content-type is not allowed by Access-Control-Allow-Headers in preflight response.
怎么办?
最佳答案
不幸的是,Slack API 端点似乎在处理来自前端 JavaScript 代码的跨源请求时出现问题——因为它没有按应有的方式处理 CORS 预检 OPTIONS 请求——所以唯一的解决方案似乎是省略 Content-Type header 。
因此看起来您需要从请求代码的 headers 部分中删除以下内容:
'Content-type': 'application/json'
该部分会触发您的浏览器执行 CORS preflight OPTIONS request .因此,为了让您的浏览器允许您的前端 JavaScript 代码发送您尝试执行的 POST 请求,https://hooks.slack.com/services API端点必须返回一个 Access-Control-Allow-Headers 响应 header ,其值中包含 Content-Type。
但是那个端点没有返回那个,所以预检失败并且浏览器就在那里停止。
通常,当从前端 JavaScript 发送到需要 JSON 的 API 端点时,将 Content-Type: application/json header 添加到请求正是您需要和应该做的。但在这种情况下并非如此——因为该 API 端点没有正确处理它。
关于javascript - 松弛传入 webhook : Request header field Content-type is not allowed by Access-Control-Allow-Headers in preflight response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45752537/