Javascript:CORS政策禁止从来源“ http ...”访问“ https ..”

时间:2019-01-26 00:36:27

标签: javascript reactjs cors

当我运行此命令时:

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

一切都按照我想要的方式发布。但是,在javascript中,当我运行发布请求时:

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."
    })

我不断收到错误消息:

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.

我认为这是问题所在:Deadly CORS when http://localhost is the origin 但是后来我尝试打开自己的ngrok并遇到了同样的错误。我也尝试安装Allow-Control-Allow-Origin chrome扩展名,但无济于事。 另外,正如您在我的代码中看到的那样,我将其设置为允许访问CORS。最后,我尝试使用Firefox,但仍然无法正常工作。有谁知道可能是什么问题?

1 个答案:

答案 0 :(得分:0)

在POST请求之前,发出OPTION请求。来自服务器标头的OPTION请求:

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

如果以下请求使用允许的方法,则...是允许的来源,并且是'application / json请求,...一切都很好!