Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
216 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...