0

I'm new to WebSockets and I want to have real-time data from traccar so I'm trying to use their WebSocket API but I couldn't connect to it. I followed their documentation https://www.traccar.org/traccar-api/.

And this is my code:

 $.ajax({
                //url: "http://[IP]:8082/api/session",
                url: "http://demo.traccar.org/api/session",
                dataType: "json",
                type: "POST",
                data: {
                    email: "useremail@email.net",
                    password: "myPassword"
                },
                success: function(sessionResponse){
                    console.log(sessionResponse);
                    openWebsocket();
                }
            });

            var openWebsocket = function(){
                var socket;
                socket = new WebSocket('ws://demo.traccar.org/api/socket');

                socket.onclose = function (event) {
                    console.log("WebSocket closed");
                };

                socket.onmessage = function (event) {
                    var i, j, store, data, array, entity, device, typeKey, alarmKey, text, geofence;
                    console.log(event.data);
                };
            };

and I'm encountering this error:

Error

halfer
  • 19,824
  • 17
  • 99
  • 186
P7rck
  • 116
  • 1
  • 5

1 Answers1

0

It looks like you're trying to send a request from a different host. It won't work because CORS is not enabled on the demo server.

The easiest workaround is set up a proxy, so both your JS app and the API are on the same host.

Anton Tananaev
  • 2,458
  • 1
  • 25
  • 48
  • Hi, I created my own server and installed traccar, i already manage to connect with the websocket. But i can only connect to it if im current logged in my server website. Im still using the same code above. I have a token in the response of making a new session. – P7rck Oct 12 '22 at 10:48