4

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.

2 Answers 2

3

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'))
Sign up to request clarification or add additional context in comments.

Comments

2

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.

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.