I am running an http server on port 8081, and am trying to get a JSON using the getJSON jQuery function. But am always running with cross domain (CORS) issue. I was thinking of using JSONP, but am not sure how am I am suppose implement it on my node.js script.
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Allow-Headers"] = "Content-Type,X-Requested-With, X-PINGOTHER";
headers["Access-Control-Max-Age"] = 86400;
response.writeHead(200, headers);
var objToJson = {"response":res };
response.write(JSON.stringify(objToJson));
This is my client side code.
jQuery.getJSON('http://localhost:8081', function(data) {
console.log(data);
});
You could adapt this PHP Script, the logic is very simple. Credits to: http://stackoverflow.com/a/1678243
if (array_key_exists('callback', $_GET)) {
// JSONP String
header('Content-Type: text/javascript; charset=utf8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Max-Age: 0');
header('Access-Control-Allow-Methods: GET');
$callback = $_GET['callback'];
echo $callback . '(' . $data . ');';
} else {
// JSON String
header('Content-Type: application/json; charset=utf8');
echo $data;
}
No idea what you're doing wrong, but I copied your code, filled the blanks and it worked for me (on Firefox 16 and Chrome 24).
Here is my CORS demo:
app.js
var http = require('http');
http.createServer(function(request, response) {
var headers = {};
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Allow-Headers"] = "Content-Type,X-Requested-With, X-PINGOTHER";
headers["Access-Control-Max-Age"] = 86400;
response.writeHead(200, headers);
var objToJson = {"response": "hello cors" };
response.write(JSON.stringify(objToJson));
response.end()
}).listen(8081)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>CORS demo</title>
</head>
<body>
view results in the console
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type=text/javascript>
jQuery.getJSON('http://localhost:8081', function(data) {
console.log(data);
});
</script>
</body>
</html>