Slack incoming webhook: Request header field Content-type is not allowed by Access-Control-Allow-Headers in preflight response

对着背影说爱祢 提交于 2019-12-28 06:00:30

问题


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);
};

I get the following error message:

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.

What to do?


回答1:


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'

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.

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.




回答2:


I am using axios and had similar issue. What worked for me is setting Content-Type header to application/x-www-form-urlencoded. found it in this thread: https://github.com/axios/axios/issues/475 It appears that this triggers "simple request" and therefore avoids triggering CORS preflight. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

HTH.



来源:https://stackoverflow.com/questions/45752537/slack-incoming-webhook-request-header-field-content-type-is-not-allowed-by-acce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!