如何从javascript发送curl请求?

时间:2018-03-05 18:33:37

标签: javascript curl

我想发送此

curl https://fcm.googleapis.com/fcm/send \
     -H "Content-Type: application/json" \
     -H "Authorization: key=<MY API KEY>" \
     -d '{ "notification": {"title": "Hello world", "body": "you got a new message", "icon": "icon/path","click_action" : "page/path"},"to" : "<DEVICE TOKEN>"}'

从js文件到我想要的任何地方。考虑到你给我的吼声,现在我尝试用这个:

        $.ajax({
            url: "https://fcm.googleapis.com/fcm/send",
            type: 'POST',
            dataType: 'json',
            headers: {
                'Access-Control-Allow-Origin' : '*',
                'Authorization': '<APY KEY>',
                'contentType': 'application/json',
            },
            data: {
                'title': 'Hello world!', 
                'body': 'you got a new message', 
                'icon': 'icon/path', 
                'click_action' : 'page/path', 
                'to' : '<DEVICE TOKEN>',
            },
            success: function (result) {
              alert(JSON.stringify(data));
            },
            error: function (error) {
               alert("Cannot get data");
            }
        });

但我收到此错误:对预检请求的响应未通过访问控制检查:否&#39; Access-Control-Allow-Origin&#39;标题存在

1 个答案:

答案 0 :(得分:1)

JavaScript中不存在Curl,您可以使用XMLHttpRequest。为了使它更容易,您可以使用jQuery发送AJAX请求。

以下是一些示例代码:

$.ajax({
  type: "POST",
  url: "http://yourdomain.com/example.php",
  data: {
    api_key: "xxxxxxxx"
  },
  success: function(data) {
    console.log(data);
    //do something when request is successfull
  },
  dataType: "json"
});