I got a Node.js / Sails.js app with a client form that submit to a Controller via Jquery ajax:
$(function () {
$("form").submit(function (e) {
e.preventDefault();
var form = $(this);
$.ajax({
url: form.attr("action"),
type: "POST",
dataType: 'json',
data: form.serialize(),
success: function(json){
alert( "Data Returned: " + JSON.stringify(json));
},
error: function(xhr, status, error) {
alert( "error" );
}
});
});
});
My controller ArticleController.js
try to get info from Flickr API :
**
* ArticleController.js
*
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
search: function (req, res) {
var searchImg = req.param("search");
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
return res.send(data);
});
}
};
But I got this error :
POST http://localhost:1337/Article/search 500 (Internal Server Error) jquery-1.10.2.js:8706
send jquery-1.10.2.js:8706
jQuery.extend.ajax jquery-1.10.2.js:8136
(anonymous function) main.js:7
jQuery.event.dispatch jquery-1.10.2.js:5095
elemData.handle
Of course I tested my controller without getJSON call and it works fine, returning simple string or JSON values.
You used JQuery ($.getJson) in your Sails-App - that isn't possible the way you want to.
JQuery uses the Browser-API to make a request, in NodeJs you don't have a browser-API and you don't have JQuery in Sails.
Replace your jQuery-Code with a HTTP-Request in NodeJS. There is a really good example in the node documentation for that: http://nodejs.org/docs/v0.4.11/api/http.html#http.request
Or you could use a library like request (https://github.com/mikeal/request)
You can't use jQuery inside nodejs : it's a browser (client-side) library !
The simplest replacement to your jQuery call would be to use the super simple and super powerfull request
module :
https://github.com/mikeal/request
But, if you really want to use jQuery inside nodejs, there is also a few solutions out there.. These really aren't the recommanded solutions to make a simple API call. But they can be used to do some scraping : parse an HTML page with all the power of jQuery.
In that eventuality, you can give a try to my buck
module, and give me some feedback..
var $ = require('buck');