Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS issue using axios with Slack API

I am using axios, from browser, to interface with Slack webhook API. When sending a post, I try to use

axios.post(url, data)

Browser/axios sends an OPTION request to the backend. Included in the OPTION request is

access-control-request-headers:content-type

However, Slack's response has

access-control-allow-origin:*

but no access-control-allow-headers header. This causes browser/XMLHttpRequest to complain

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

Seems like one solution is to tell axios to not send a content-type header in this case, but I can't figure out how to do that.

Thanks.

like image 442
Overclocked Avatar asked Dec 10 '22 13:12

Overclocked


1 Answers

Basically, you need to remove content type header, which can only be achieved using a hacky way:

const url = 'https://hooks.slack.com/services/{YOUR_WEBHOOK}'
const data = {
  "text": "yo some text",
}
axios.post(url, JSON.stringify(data), {
  withCredentials: false,
  transformRequest: [(data, headers) => {
    delete headers.post["Content-Type"]
    return data
  }]
})
like image 172
Ming Avatar answered Dec 18 '22 07:12

Ming