3

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?

3
  • github.com/request/request Commented Nov 19, 2016 at 8:52
  • ajax is for frontend to query backend. since nodejs is alrdy in backend, why would u need ajax? Commented Nov 19, 2016 at 8:52
  • @Mox He/she probably wants to send a typical http request to another server or an internal application-level route. Commented Nov 19, 2016 at 8:56

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.