I'm creating a simple game with a NodeJS backend. The game itself needs to talk to the server through XHR requests (or something similar). So, my Node server takes requests with an action variable (JSON data) and then translates that to an action and returns the result to the front.
This idea is working fine if I call the action on the server using a request sent by Postman. So, I got the XHR code from Postman and implemented it on my game page and for some reason it becomes stuck on pending (in the chrome network tab). Here's the client and server code:
CLIENT:
var data = JSON.stringify({
"action": "getCards"
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://somedomain.ddns.net/");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "03f12253-f351-3e60-5d00-956b01ad6311");
xhr.send(data);
SERVER:
https.createServer(options, function(req, res) {
handleRequest(req, res);
}).listen(port, hostname);
function handleRequest(req, res) {
var queryData = '';
if (req.method == 'POST') {
req.on('data', function(data) {
queryData += data;
});
req.on('end', function() {
var parsed = JSON.parse(queryData);
if (!parsed.action) { res.writeHead('200'); res.end('No action'); return; }
switch (parsed.action) {
case 'getCards':
res.writeHead('200', {'Content-Type': 'application/json'});
mongo.getMongoCollection('cards', function(err, coll) {
if (err) { console.log('Something went wrong while connecting to the DB:', err); return; }
coll.find({}, function(err, result) {
if (err) {console.log('Couldn\'t find', err); return; }
result.toArray(function(err, result) {
console.log('Got this list', result);
res.end(JSON.stringify({err: err, res: result}));
});
});
});
break;
}
});
}
}
I have no idea what's going wrong based on the fact that I can do the exact request with Postman.
via Dries
No comments:
Post a Comment