Node.js Express jquery ajax request not working

Problem

Working on a RESTful api, When I access this in my browser at 96.126.111.211/getLeaderBoard

it works fine and gives me the JSON data from my mongo database.

Though when I try a jquery ajax request like this http://jsfiddle.net/yVQ5T/ I get a jsonp error

Error: jQuery171037622810900211334_1363808084624 was not called

Here is the code on the server side

getLeaderBoard(req, res)
{
    this.db.collection(this.settings.userTable, function(err, collection) => {
        collection.find().toArray(function(err, items) {
            res.writeHead(200, {'Content-Type': 'application/javascript'});

            res.write(JSON.stringify(items));

            res.end();
        });
    });
}
Problem courtesy of: Ciarán

Solution

Your url serves regular JSON not JSONP, you have to place it in a call to the callback function, e.g.

jQuery171037622810900211334_1363808084624 ([{"userId":"100821494565115211032","winCount":4,"_id":"5148caa1a1651dff12000002"}]);

Since the callback name is dynamically generated you'll have to read them from the request.

Solution courtesy of: Musa

Discussion

If you are using Express 3.0 you can look at response.jsonp which is identical in use to response.json. If you are accessing your server from another domain then you will have to use the JSONP protocol due to cross domain request restrictions that browsers implement as safety measures.

In express 2.x you will need to enable JSONP response handling via app.enabled("jsonp callback") and then use response.json

3.0 Api

2.0 Api

Discussion courtesy of: Brandon Buck

This recipe can be found in it's original form on Stack Over Flow.