Jiew Meng
Jiew Meng

Reputation: 88217

AJAX Helper for NodeJS, instead of jQuery?

I just want to do something like $.get/post on a server side script. Is there a better way instead of including the whole jQuery? I prefer not to use the messy get xml http requests stuff manually either.

Upvotes: 4

Views: 304

Answers (2)

Kyle Weller
Kyle Weller

Reputation: 2623

require http. As found in their documentation you can make a request like the following:

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

There is a simple GET as well:

http.get("http://www.google.com/index.html", function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

You can also look into Express.js and request, there really are many options that you could use besides jquery.

Upvotes: 2

generalhenry
generalhenry

Reputation: 17319

The equivalent to jquery.ajax in node.js is request

It sits on top of the node core http and makes things nicer to work with. Allowing for both callback and streaming requests.

examples:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Print the google web page.
  }
})

request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))

Upvotes: 3

Related Questions