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.
This can be done by Ajax request, we are sending data to our node server, and it also gives back data in response to our Ajax request. Step 1: Initialize the node modules and create the package. json file using the following command.
NodeJs is an open-source framework based on JavaScript v8 engine. AJAX is a web development technique for making asynchronous calls to the server. jQuery is a JavaScript library for designing and make some web development tasks easy. It makes it possible to run javascript outside of the browser.
js: We can use jQuery in Node. js using the jquery module. Note: Use the 'jquery' module not the 'jQuery' module as the latter is deprecated.
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(); };
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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With