4

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

neomat
  • 103
  • 1
  • 1
  • 6
  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – jmargolisvt Mar 05 '18 at 18:37
  • The error message does not mean your request, so you don't have to put these headers in your request. Instead it refers to the response from firebase, which you are trying to access. To enable CORS, you can have a look here: https://stackoverflow.com/questions/42755131/enabling-cors-in-cloud-functions-for-firebase – Martin Seeler Mar 05 '18 at 20:10
  • Possible duplicate of [Executing curl from Javascript?](https://stackoverflow.com/questions/2804639/executing-curl-from-javascript) – Mehdi Dehghani Feb 26 '19 at 11:39

1 Answers1

3

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"
});
Joost Meijer
  • 375
  • 2
  • 15