neomat
neomat

Reputation: 103

How can I send a curl request from javascript?

I would like to send this

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>"}'

from a js file to wherever I want. Considering the ideas you are giving me bellow, now I'm trying with this:

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

but I'm getting this error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present

Upvotes: 4

Views: 20666

Answers (1)

Joost Meijer
Joost Meijer

Reputation: 395

Curl doesn't exist in JavaScript, instead you can use XMLHttpRequest. To make it even more easy, you can use jQuery to send an AJAX request.

Here is some example code:

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

Upvotes: 3

Related Questions