问题描述
我尝试通过浏览器中的访存API发布松弛消息:
I try to post a slack message via the fetch API in a browser:
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
标头。
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.
因此,您似乎需要从请求代码的标头
部分中删除以下内容:
So it looks like you need to remove the following from the headers
part of your request code:
'Content-type': 'application/json'
那个'Content-type':'application / json'
部分触发您的浏览器执行。因此,要让您的浏览器允许您的前端JavaScript代码发送您要执行的 POST
请求,请使用 https://hooks.slack .com / services
API终结点必须返回 Access-Control-Allow-Headers
响应标头,其中包含 Content-Type
的值。
That 'Content-type': 'application/json'
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 header, 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 particular API endpoint doesn’t handle it properly.
这篇关于传入Webhook松弛:在飞行前响应中,Access-Control-Allow-Headers不允许请求标头字段Content-type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!