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:
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.
Related
I have a multi-tenant Laravel web application, using stancl/tenancy for multi-tenancy support in Laravel. I also created a separate traccar server. Each tenant has a different user in the traccar server they have their own subdomains and each tenant have separates sessions. I have a problem about session cookie authentication I use the api POST api/session to create a session of the user and connect to traccar websocket and establish connection but it cannot work with my multitenancy setup.
This is my code for websocket connection:
var ajaxTraccar = function (method, url, callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback(JSON.parse(xhr.responseText));
}
};
if (method == 'POST') {
xhr.setRequestHeader('Content-type', 'application/json');
}
xhr.send()
};
var openWebsocket = function(token){
ajaxTraccar('GET', 'https://traccarwebsite.server/api/server', function(server) {
ajaxTraccar('GET', 'https://traccarwebsite.server/api/session?token=' + token, function(user) {
ajaxTraccar('GET', 'https://traccarwebsite.server/api/devices', function(devices) {
var socket = new WebSocket('wss://traccarwebsite.server/api/socket');
socket.onclose = function (event) {
console.log('socket closed');
};
socket.onmessage = function (event) {
console.log("Socket Messaged);
};
});
});
});
};
function initMap() {
$.ajax({
//url: "http://[IP]:8082/api/session",
url: "https://traccarwebsite.server/api/session",
dataType: "json",
type: "post",
async: false,
data: {
email: "{{ $email }}",
password: "{{ $pass }}",
},
success: function(sessionResponse){
openWebsocket(sessionResponse.token)
}
});
}
Scenario: suppose I have two companies and open them at the same time. When I try to establish a WebSocket connection only one will connect and the other tenant can listen to the messages from the websocket.
How can I separate the WebSockets of tenants? Do I need to create a Proxy server?
Is this diagram viable?
What can I try next?
I am trying to write on my firebase real time database through https triggered function with Admin SDK, When a button (id=change) is clicked.
This is is the ajax get method in client side code
$('#change').click(function(){
$.ajax({
url: 'https://<CLOUD FUNCTION URL>/verifyuser?uid='+user.uid,
type: "GET",
cache: false,
dataType: "text",
crossDomain: true,
success : function(result){console.log(result);},
error : function(error){console.log(error);}
});
});
Given below is my firebase cloud function which triggers on http request.
const functions = require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const cors=require('cors')({origin: true});
exports.verifyuser = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const uid=req.query.uid;
admin.database.ref('/tathva17/users/'+uid+'/hospitality').set(
{'status':'confirmed'}).then(function(){
res.status(200).send("Success!");
});
});
});
Error shown in my console after clicking button (id="change")
error seen in Logs
Try using ajax like this, as a cross domain access, you need to set dataType as jsonp
$.ajax({
url: 'https://<CLOUD FUNCTION URL>/verifyuser?uid='+user.uid,
type: "GET",
cache: false,
dataType: "jsonp",
success : function(result){console.log(result);},
error : function(error){console.log(error);}
});
I'm just wondering what would be the better approach to calling a Web api method? The pros and cons?
option1.
Calling the web api from an ajax post
$.ajax({
url: 'localhost/api/user/adduser',
type: 'POST',
data: JSON.stringify({ Id: Id }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function () {
alert("error");
}
});
or option2.
An ajax post to a client controller and then use a rest client to call the web api
$.ajax({
url: 'user/adduser/',
type: 'POST',
data: JSON.stringify({ Id: Id }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function () {
alert("error");
}
});
And calling the api
public ActionResult addUser(int id)
{
var api = new RestClient("http://localhost:60081/api/");
var request = new RestRequest("/user/adduser", Method.POST);
var result = new User();
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(id);
var resp = api.Execute(req);
}
If you control the api and you don't need to further enrich the API call, my personal preference is option 1 as it saves unnecessary code.
If it's an external api such as Instagram's API, I prefer option 2- as then I can enrich the API with additional info like AccessToken's that I want private (rather than embedded in the JS).
I am sending data from the client to the server.
// client
var messageObj = {};
messageObj.fromUserId = 1;
messageObj.messageContent = "print this";
$.ajax({
url: "/sendMessage",
type: "POST",
data: JSON.stringify(messageObj)
})
// server
app.post('/sendMessage', function (req, res, next) {
console.log(req.body);
return res.status(200);
});
Why is the console.log output, this:
{ '{"fromUserId":1,"messageContent":"print this"}': '' }
and not this ? (and how can I get it to this ?)
{"fromUserId":1,"messageContent":"print this"}
The default, unless you specify something else, is to send the data URI-encoded and to tell the server that's how it's being sent. If you're going to send JSON, you need to tell both the browser (and jQuery) and the server that by specifying contentType:
$.ajax({
url: "/sendMessage",
type: "POST",
contentType: "application/json",
data: JSON.stringify(messageObj)
})
I am using Ajax call to post data from client side to node server and trying to receive data at server end, manipulate it(do some db query) and then return the response.
client side code :
$.ajax({
type: "post",
url: "http://localhost:8888/ajaxRequest",
dataType: "json",
data: {name: "Manish", address: {city: "BBSR", country: "IN"}}
}).done(function ( data ) {
console.log("ajax callback response:" + data);
});
server side :
var port = 8888;
var server = http.createServer();
server.on('request', request);
server.listen(port);
function request(request, response) {
var store = '';
response.writeHead(200, {"Content-Type": "text/json"});
request.on('data', function(data) {
store += data;
});
request.on('end', function() {
console.log(store);
response.end(store);
});
}
Problem : when I am consoling "store" variable in request end function I am getting something like this:
name=Manish&address%5Bcity%5D=BBSR&address%5Bcountry%5D=IN
I just want the same data at the server side what I sent in the Ajax 'data' parameter. I also tried, queryString.parse, JSON.parse() but no help. I just want my output as :
{name: "Manish", address: {city: "BBSR", country: "IN"}}
You need to tell jQuery that this is an JSON request:
$.ajax({
type: "post",
url: "http://localhost:8888/ajaxRequest",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({name: "Manish", address: {city: "BBSR", country: "IN"}})
}).done(function ( data ) {
console.log("ajax callback response:" + data);
});
This way, your request body will reach the server with the stringified JSON, so you'll be able to do the following:
request.on('end', function() {
store = JSON.parse(store);
console.log(store); // ta-daaa, Object!
response.end(store);
});
Have you tried something like:
...
response.end(JSON.stringify(store));