Slack 传入 webhook:请求 header 字段 Content-type 不允许在预检响应中被 Access-Control-Allow-Headers
Slack incoming webhook: Request header field Content-type is not allowed by Access-Control-Allow-Headers in preflight response
我尝试 post 通过在浏览器中获取 API 一条松弛消息:
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 代码的 cross-origin 请求时似乎被破坏了——因为它不处理 CORS 预检 OPTIONS
应有的要求——所以唯一的解决办法似乎是省略 Content-Type
header.
因此您似乎需要从请求代码的 headers
部分删除以下内容:
'Content-type': 'application/json'
该部分会触发您的浏览器执行 CORS preflight OPTIONS
request。因此,为了让您的浏览器允许您的前端 JavaScript 代码发送您尝试执行的 POST
请求,https://hooks.slack.com/services
API 端点必须 return Access-Control-Allow-Headers
响应 header 在其值中包含 Content-Type
。
但是那个端点没有 return,所以预检失败,浏览器就停在那里。
通常当从前端 JavaScript 发布到期望 JSON 的 API 端点时,将 Content-Type: application/json
header 添加到请求正是你需要做和应该做的。但在这种情况下不是——因为 API 端点没有正确处理它。
我正在使用 axios
并且遇到了类似的问题。对我有用的是将 Content-Type
header 设置为 application/x-www-form-urlencoded
。在这个线程中找到它:https://github.com/axios/axios/issues/475
看来这会触发 "simple request",因此避免触发 CORS 预检。
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
HTH.
我尝试 post 通过在浏览器中获取 API 一条松弛消息:
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 代码的 cross-origin 请求时似乎被破坏了——因为它不处理 CORS 预检 OPTIONS
应有的要求——所以唯一的解决办法似乎是省略 Content-Type
header.
因此您似乎需要从请求代码的 headers
部分删除以下内容:
'Content-type': 'application/json'
该部分会触发您的浏览器执行 CORS preflight OPTIONS
request。因此,为了让您的浏览器允许您的前端 JavaScript 代码发送您尝试执行的 POST
请求,https://hooks.slack.com/services
API 端点必须 return Access-Control-Allow-Headers
响应 header 在其值中包含 Content-Type
。
但是那个端点没有 return,所以预检失败,浏览器就停在那里。
通常当从前端 JavaScript 发布到期望 JSON 的 API 端点时,将 Content-Type: application/json
header 添加到请求正是你需要做和应该做的。但在这种情况下不是——因为 API 端点没有正确处理它。
我正在使用 axios
并且遇到了类似的问题。对我有用的是将 Content-Type
header 设置为 application/x-www-form-urlencoded
。在这个线程中找到它:https://github.com/axios/axios/issues/475
看来这会触发 "simple request",因此避免触发 CORS 预检。
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
HTH.