Posting chatMessage to Slack using Fetch in vanilla JS

Viewed 241

As the title states, I am trying to post messages to a Slack chat. I had code that work with fetch but I cannot seem to find it now. Below is my current code:

fetch('http://slack.com/api/chat.postMessage', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'token': 'REMOVED TOKEN',
      'channel': 'bot',
      'text': 'This is a test.'
    }
  });

The program is never sending a message now, no matter what I change or add to the code. I want to get this done with vanilla JS, I do not want to use a framework.

I hope my question is clear, if not, please let me know.

1 Answers

I have finally figured out the answer to this.

Firstly, I was using the incorrect link. It was missing a ?.

It should be (for Chrome): http://slack.com/api/chat.postMessage?token=...&channel=...&text=...

For Firefox, it would be:

https://cors-anywhere.herokuapp.com/http://slack.com/api/chat.postMessage?token=...&channel=bot&text=test message

The above fix overrides the CORS issue by using a proxy, so this should work on Chrome and Firefox.

Alternatively, the following is also an option:

fetch('https://cors-anywhere.herokuapp.com/http://slack.com/api/chat.postMessage?token=...&channel=bot&text=test message', {
    headers: {
      'Access-Control-Allow-Origin': '*'
    }
  });

Which also overrides the CORS issue by using a proxy.

Related