jQuery.ajax() in node.js?
Is it possible to use jQuery.ajax()
in node.js exactly as it is syntax-wise?
I am trying to share non-UI browser code with node.js. I do not want to replace all the existing function calls with my own wrapper.
Currently when I try it, it would say "No Transport" by default because jQuery does domain detection. If I turn it off by setting jQuery.support.cors
it would say XMLHttpRequest.open() not available.
Solution 1:
I was able to solve the "No Transport" issue using the XMLHttpRequest module, like this:
var $ = require('jquery'),
XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
$.support.cors = true;
$.ajaxSettings.xhr = function() {
return new XMLHttpRequest();
};
Solution 2:
also consider najax, a wrapper for the node request module which allows jquery style syntax for server-side requests
https://github.com/alanclarke/najax
var najax = require('najax');
najax('http://www.google.com', function(html){ console.log(html); });
najax('http://www.google.com', { type:'POST' }, function(html){ console.log(html); });
najax({ url:'http://www.google.com', type:'POST', success: function(html){ console.log(html); });
najax({ url:'http://www.google.com', type:'POST' }).success(function(resp){}).error(function(err){});
najax.get, najax.post, najax.put, najax.delete...
Solution 3:
If you want the exact jQuery.ajax syntax, try https://github.com/driverdan/node-XMLHttpRequest
But really if you have control over what you're calling ajax for, you should do it with node's http.request
or a module like request
Solution 4:
I am also sharing code between a browser and nodejs and also use JQuery for Ajax calls. JQuery requires a window which I use from domino.
update:
if (typeof module !== 'undefined' && module.exports)
{
if (typeof global !== 'undefined' && typeof global.process !== 'undefined' &&
Object.prototype.toString.call(global.process) === '[object process]') {
var domino = require('domino');
var window = domino.createWindow('<html></html>');
var document = window.document;
var $ = require('jquery')(window);
var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
$.support.cors = true; // cross domain, Cross-origin resource sharing
$.ajaxSettings.xhr = function() {
return new XMLHttpRequest();
};
}
}