0

When I run this command:

curl -X POST -H 'Content-type: applicatiojson' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/XXXXXXXXX/XXX/XXXX

Everything posts the way I want. But, in javascript, when I run the post request:

fetch('https://hooks.slack.com/services/XXXXXXXXX/XXX/XXXX', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "*"
      },
      text: "Hello, world."
    })

I keep getting the error:

Access to fetch at 'https://hooks.slack.com/services/XXXX/XXXX/XXXX' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I thought this was the problem: Deadly CORS when http://localhost is the origin But then I tried opening my own ngrok and got the same error. I also tried installing the Allow-Control-Allow-Origin chrome extension to no avail. Also, as you can see in my code, I set it to allow access for CORS. Lastly, I tried on firefox but still wouldn't work. Does anyone know what the problem could be?

Slaknation
  • 2,124
  • 3
  • 23
  • 42
  • Have you tried setting `mode: 'cors'` in the request object? See https://developer.mozilla.org/en-US/docs/Web/API/Request/mode – Matt Holland Jan 26 '19 at 00:41
  • @MattHolland Just tried it and it didn't work: /oauth.access', {mode: 'cors',method: 'POST', ... – Slaknation Jan 26 '19 at 00:46
  • Check what HTTP response you get for `curl -i -X OPTIONS -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/XXXXXXXXX/XXX/XXXX` – sideshowbarker Jan 26 '19 at 00:57
  • 1
    Omit the Content-Type header from your fetch call. The answer at https://stackoverflow.com/questions/45752537/slack-incoming-webhook-request-header-field-content-type-is-not-allowed-by-acce/45752919#45752919 explains why. Also omit the Access-Control-Allow-\* headers from your fetch call. The Access-Control-Allow-\* headers are response headers, not request headers. The only effect that trying to set them as request headers will have is that it’ll trigger a CORS preflight OPTIONS request. And the as noted in the answer I mentioned, the Slack API doesn’t support receiving OPTIONS requests. – sideshowbarker Jan 26 '19 at 01:04

1 Answers1

0

Before POST Request an OPTION request is made. OPTION request receive from server headers:

    "Accept": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "*"

If following request use allowed method, ... is an allowed origin and is an'application/json request, ... everything is all right!

sensorario
  • 20,262
  • 30
  • 97
  • 159