Organizational Research By

Surprising Reserch Topic

http request with node


http request with node  using -'javascript,http,node.js,httpclient'

asked Sep 22, 2015 by vibhorsingh
0 votes
4 views



Related Hot Questions

4 Answers

0 votes

Use the http client.

Something along these lines:

var http = require('http');
var client = http.createClient(3000, 'localhost');
var request = client.request('PUT', '/users/1');
request.write("stuff");
request.end();
request.on("response", function (response) {
    // handle the response
});
answered Sep 22, 2015 by nimisha.jagtap
0 votes

For others googling this question, the accepted answer is no longer correct and has been deprecated.

The correct method (as of this writing) is to use the http.request method as described here: nodejitsu example

Code example (from the above article, modified to answer the question):

var http = require('http');

var options = {
  host: 'localhost',
  path: '/users/1',
  port: 3000,
  method: 'PUT'
};

callback = function(response) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();
answered Sep 22, 2015 by param.oncemore
0 votes
var http = require('http');
var client = http.createClient(1337, 'localhost');
var request = client.request('PUT', '/users/1');
request.write("stuff");
request.end();
request.on("response", function (response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
 });
});
answered Sep 22, 2015 by nimisha.jagtap
0 votes

A small request function in CoffeeScript

http = require "http"
request = (url, done) ->
  throw "Invalid URL" unless (m = url.match /^http:\/\/([^\/]+)(.*)/)
  http.request({ host:m[1], path:m[2] }, (res) ->
    str = ''
    res.on 'data', (c) -> str += c
    res.on 'end', -> res.body = str; done res
  ).end()

and if you hate CoffeeScript (puzzling why...) here's a JavaScript version

var http = require("http");
var request = function(url, done) {
  var m;
  if (!(m = url.match(/^http:\/\/([^\/]+)(.*)/))) {
    throw "Invalid URL";
  }
  http.request({
    host: m[1],
    path: m[2]
  }, function(res) {
    var str = '';
    res.on('data', function(c) {
      str += c;
    });
    return res.on('end', function() {
      res.body = str;
      done(res);
    });
  }).end();
};
answered Sep 22, 2015 by akhilesh

...