Node.js server seems to function incorrectly on c9

nodejs

#1

I’m using this official c9 example here.

The only code I have on c9 is as follows and is pulled straight from the example.

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(process.env.PORT, process.env.IP);

If you then run it and access the project application link in a browser, it will display hello world just fine. However if I try to perform a HTTP GET request on it using jQuery I get an error. The jQuery i’m using is below.

$.get("https://link-to-project-application", function(resText){
    alert("Success");    
}).fail(function(){
    alert("Failed");
});

If I run it while the c9.io server is running, I get an alert message saying Failed. I know the jQuery is not the issue since if I change the URL to a test service such as http://httpbin.org/get then it returns Success.

This would indicate a problem with c9, or me doing something stupid on c9.

A very interesting thing I came across is this. If you put a debug statement into the server code, console.log(“Request Received”), You get some interesting behaviour. The code with the debug statement is below:

var http = require('http');
http.createServer(function (req, res) {
    console.log("Request Received");
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(process.env.PORT, process.env.IP);

This produces the following results. When accessed via browser the debug statement gets printed twice, indicating that it may have retried the request or some other similar behaviour. If I however, make the request with jQuery the debug statement gets printed once, indicating that I am copying the URL correctly into my jQuery code. I think the failed request problem and this may be linked.

Any idea if this is a bug with c9 or am I being oblivious to something obvious?


#2

I found a fix myself.

Adding res.setHeader(“Access-Control-Allow-Origin”, “*”); to the top of the http server fixed the issue