Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.ajax like function for Node js?

is Node js has any function just like $.ajax? I think Node js is fully javascript written and $.ajax jquery is also is fully javascript written. Then maybe node js has any function just like $.ajax. Is it wrong?

like image 884
Otgonbayar Lamjav Avatar asked Jun 13 '26 09:06

Otgonbayar Lamjav


1 Answers

Technically, AJAX is a browser-only thing based on a particular API in the browser. So, I will assume that what you're really asking about is for a simple way to make HTTP requests of other HTTP servers from within node.js.

To make such a request, you can either use the built-in http.get() (in the http module) or you can use a higher level add-on module request(). The request module is built on top of the http module, but offers many more features and, for many things, it much easier to use.

Among the list of features in the request module, you will find: stream support, form encoding/decoding, http auth, custom headers, OAuth, signing, redirects, queryString, gzip, etc...

Here's an example:

const request = require('request');

request({method: 'GET', uri: 'http://www.google.com'}, function(err, response, body) {
    // handle response here
});

Since promises are now the more modern tool for handling asynchronous operations in Javascript, here's an example using promises:

const rp = require('request-promise');

rp({method: 'GET', uri: 'http://www.google.com'}).then(body => {
    // handle response here
}).catch(err => {
    // error here
});

EDIT Jan, 2020 - request() module in maintenance mode

FYI, the request module and its derivatives like request-promise are now in maintenance mode and will not be actively developed to add new features. You can read more about the reasoning here. There is a list of alternatives in this table with some discussion of each one. I have been using got() myself and it's built from the beginning to use promises and is simple to use.

like image 88
jfriend00 Avatar answered Jun 15 '26 22:06

jfriend00