I am new to node.js and json and am having trouble returning the JSON object to the client html page that's using $.getjson.
In the example below when i point the same code at the api.twitter.... url I can query and return the value. But when I point this to my own node.js back end that's spitting out the same JSON the alert('inside callback: ' + data[0].is_translator); does not pop up. What am I doing wrong here? I would really appreciate some help here.
This is script code in my test.html that's calling $.getJSON.
<script>
//var url = "http://localhost:5000/searchPlaces?callback=?";
function abc(result) {
//var url = "http://localhost:5000/random"
var url = "http://api.twitter.com/1/statuses/21947795900469248/retweeted_by.json?callback=?";
alert('before $.getjson');
$.getJSON(url, function(data) {
alert('hello');
alert('inside callback: ' + data[0].is_translator);
abc(result.data);
})
}
abc();
</script>
This is the code from my node.js backend:
var http = require("http");
var url = require("url");
var port = process.env.PORT || 8888
function start(route, handle){
function onRequest(request, response) {
var postData = "";
var pathname = url.parse(request.url).pathname;
console.log("Request received for:" + pathname + " receieved.");
response.writeHead(200, {"Content-Type": "application/json"});
var otherObject = {"is_translator":false,"id":644233,"followers_count":77};
response.write(
JSON.stringify({
anObject: otherObject
})
);
response.end();
// route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(port);
console.log("Server had started. Port:" + port);
}
exports.start = start;
Callback for $.getJSON() is called only if the JSON is valid. The url for your twitter api http://api.twitter.com/1/statuses/21947795900469248/retweeted_by.json?callback=? gives a JSON with the following error on JSONlint.org
Parse error on line 1:
([ { "is
^
Expecting '{', '['
You should maybe $.get() the url and then validate JSON yourself before using it.