Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS return JSONP NOT using express

Im trying to call my nodejs server and show the results from an angularjs app. ive been following an example, but when i change the example code for my code, it always calls the error callback. i have a feeling its something wrong with my server, but i cant make it work, its nodejs without express or other libraries, and all other answers involve using express. how can i make it work without using express?

the code in angularjs, where i call the server:

app.controller('Main', function ($scope, $http) {
    $scope.init = function() {        
        //var api = 'http://api.trakt.tv/calendar/premieres.json/7c989229f2fa626832e7576eb59820e9/20131103/30/?callback=JSON_CALLBACK';        
        $http.jsonp('http://localhost:8888/selectAllLocations?callback=JSON_CALLBACK').success(function(data) {
            console.log(data);
        }).error(function(error) {
            console.log('My error: ' + error);
        });
    };

});

if i use the value in the var api, the result is ok and success is called, not with mine.

This is the code in my nodejs server.

var result = sequelize.query(query, null, options, parameters)
.success(function (rows) {        
    if (type == 'select') {
        response.writeHead(200, { "Content-Type": "application/json" });
        response.write(JSON.stringify(rows));
        response.end();
    } else if (type == 'modify') {
        response.writeHead(200, { "Content-Type": "text/html" });
        response.write("Query was successful");
        response.end();
    }
}
).error(function (e) {
    console.log("An error occured: ", e);
    response.writeHead(404, { "Content-Type": "text/html" });
    response.write("There was an error man, shits on fire yo ---> " + e);
    response.end();
}
);

Im pretty sure i have to wrap the json result in a function, but i dont know how, and i cant even know the function name, as this is all i get in my server:

path: /selectAllLocations params: {"callback":"angular.callbacks._0"}

I understand im returning the pure json, and i can see it in chrome in my response, so, there is something preventing it from calling the success function. Can somebody point me in the right direction?

like image 751
Toddy Avatar asked Aug 07 '26 07:08

Toddy


1 Answers

The function name is specified as the callback parameter.

 response.write(params.callback + '(' + JSON.stringify(rows) + ')');
like image 158
Dan Avatar answered Aug 08 '26 21:08

Dan