Panickos Neophytou
Panickos Neophytou

Reputation: 525

Replacement for $.ajax() in Node.js

I have been using jQuery's $.ajax() functionality to make asynchronous http requests from my Node server to other external API servers.

I now want to upgrade my libraries but I'm getting

....
/jquery/node_modules/jsdom/lib/jsdom/level1/core.js:418
   set nodeName() { throw new core.DOMException();},
               ^^

SyntaxError: Setter must have exactly one formal parameter.
  1. How can I fix this error?
  2. Is there any library that is equally flexible as $.ajax() is? I'm particularly interested in the promise and $.ajaxPrefilter() functionalities.

Upvotes: 1

Views: 1671

Answers (1)

Tyler
Tyler

Reputation: 11509

Yes, node has a module called request that can do a lot more than you're probably used to with $.ajax. Basic example from their page:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
  }
})

https://github.com/request/request

As far as promises go, you can promisify anything you want with a library like bluebird: http://bluebirdjs.com/docs/getting-started.html

jQuery on the server is wholly unnecessary -- just tear the bandaid off quickly and it'll hurt less :)

Edit

Adding defaults is very easy. Just do

var req = request.defaults({
  token: myToken,
  ...
})

var payload = { ... }

req.get(payload, function(err, res, body){ 
  ... 
})

Upvotes: 2

Related Questions