How to fix CORS Policy error when doing POST with Ajax on Jquery

21.02.2020 03:06
#AJAX #JQUERY #ASP.NET #MVC #HATA

How to fix CORS Policy error when doing POST with Ajax on Jquery

Access to XMLHttpRequest at 'https://onesignal.com/api/v1/notifications' from origin 'https://www.yavuzceliker.com.tr' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Our error occurs as shown above.

This error is generally related to the access permission between websites with two different domains or two different protocols or even different ports. CORS, that is, Cross Origin Resource Sharing, can be translated as an Kökenler Arası Kaynak Paylaşımı with Turkish.

The code where the error occurs is as follows.

var Veri = {
                "app_id": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                "headings": { "en": "Deneme Başlık EN","tr":"Deneme Başlık TR" },
                "url": "https://www.siteniz.com",
                "contents": { "en": "Deneme içerik EN", "tr": "Deneme İçerik TR" },
                "included_segments":"Active Users"
            };
            $.ajax(
                {
                    url: 'https://onesignal.com/api/v1/notifications',
                    crossDomain: true,
                    type: 'POST',
                    dataType: 'json',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization':'Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'},
                    data:Veri, //The line that causes error
                    success: function (data) {
                        alert("Gönderildi");
                    },
                    Error: function (data) {
                        alert("Hata Oluştu");
                    }
                });


As shown above, the code line causing the error is the line where the data to be posted is added. What causes the error here is that the data sent is a javascript object. The command we will use to solve this situation is the following.

JSON.stringfy(obj);

Converts the javascript object entered into the purpose of this command into string format. We will change our command line that gives the error mentioned above as follows.

JSON.stringfy(Veri);

After doing this process, we will see that our problem is solved.