http module of NodeJS

Keywords: OpenSSL SSL JSON Attribute

Article directory

1 http module

1.1 basic usage

1.1.1 module attributes

1.1.1.1 properties of HTTP request

headers: the header information of the HTTP request.
url: the path of the request.

1.1.2 module method

1.1.2.1 method of HTTP module

Create server (callback): create a server instance.

1.1.2.2 method of server instance

listen(port): start the server to listen to the specified port.

1.1.2.3 HTTP response method

setHeader(key, value): Specifies the HTTP header information.
write(str): Specifies the content of the HTTP response.
end(): send HTTP response.

1.1.3 processing GET requests

HTTP module is mainly used to build HTTP services. Using Node.js to build HTTP server is very simple.

var http = require('http');

http.createServer(function (request, response){
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8080, "127.0.0.1");

console.log('Server running on port 8080.');
  • The first line of the above code, var http = require("http"), means to load the http module.
  • Then, call the createServer method of the HTTP module, create a server instance, and assign it to the variable http.
  • The ceatserver method takes a function as a parameter whose request parameter is an object that represents the HTTP request of the client
  • The response parameter is also an object that represents the HTTP response on the server side. The response.writeHead method indicates that the server responds to an HTTP header; the response.end method indicates the specific content of the server's response and closes the dialog after the response is completed.
  • The last listen(8080) indicates to start the server instance and listen to the 8080 port of the machine.
    Save the above lines of code into the file app.js, and then call the file with node, and the server starts to run.
$ node app.js

At this time, the command line window will display a prompt "Server running at port 8080." Open the browser, visit http://localhost:8080, and the webpage shows "Hello world!".
The above example is to generate a web page on the spot, or write a web page in advance, store it in a file, and then use the fs module to read the web page file and return it.

var http = require('http');
var fs = require('fs');

http.createServer(function (request, response){
  fs.readFile('data.txt', function readData(err, data) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end(data);
  });
}).listen(8080, "127.0.0.1");

console.log('Server running on port 8080.');

The following modification is to display different content according to the request of different websites, which is equivalent to making a prototype of a website.

var http = require("http");
http.createServer(function(req, res) {
  // homepage
  if (req.url == "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Welcome to the homepage!");
  }
	// About page
  else if (req.url == "/about") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("Welcome to the about page!");
  }
  // 404 mistake
  else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("404 error! File not found.");
  }
}).listen(8080, "localhost");

The callback function's req uest object, which has the following properties.

  • url: the url of the request
  • Method: method of HTTP request
  • Headers: all HTTP headers of the HTTP request.

1.1.4 processing POST requests

When the client uses POST method to send data, the server can set monitoring function for data and end events.

var http = require('http');

http.createServer(function (req, res) {
  var content = "";

  req.on('data', function (chunk) {
    content += chunk;
  });

  req.on('end', function () {
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.write("You've sent: " + content);
    res.end();
  });

}).listen(8080);

The data event will be triggered every time a piece of data is received in the data receiving process, and the received data will be passed into the callback function. The end event is triggered after all data is received.
With a little modification of the above code, you can make the function of file upload.

"use strict";

var http = require('http');
var fs = require('fs');
var destinationFile, fileSize, uploadedBytes;

http.createServer(function (request, response) {
  response.writeHead(200);
  destinationFile = fs.createWriteStream("destination.md");
  request.pipe(destinationFile);
  fileSize = request.headers['content-length'];
  uploadedBytes = 0;

  request.on('data', function (d) {
    uploadedBytes += d.length;
    var p = (uploadedBytes / fileSize) * 100;
    response.write("Uploading " + parseInt(p, 0) + " %\n");
  });

  request.on('end', function () {
    response.end("File Upload Complete");
  });
}).listen(3030, function () {
  console.log("server started");
});

1.2 request

1.2.1 get()

The get method is used to make a get request.

function getTestPersonaLoginCredentials(callback) {
  return http.get({
    host: 'personatestuser.org',
    path: '/email'
  }, function(response) {
    var body = '';

    response.on('data', function(d) {
      body += d;
    });

    response.on('end', function() {
      var parsed = JSON.parse(body);
      callback({
        email: parsed.email,
        password: parsed.pass
      });
    });
  });
},

1.2.2 request()

The request method is used to issue HTTP requests. Its format is as follows.

http.request(options[, callback])

The options parameter of the request method can be an object or a string. If it's a string, it means that it's a URL, and Node will automatically call url.parse() to handle this parameter.
The options object can set the following properties

  • host: the domain name or IP address to which the HTTP request is sent. The default is localhost.
  • hostname: this attribute will be parsed by url.parse(), with priority higher than host.
  • Port: the port of the remote server. The default is 80.
  • localAddress: local network interface.
  • socketPath: Unix network socket, the format is host:port or socketPath.
  • Method: Specifies the method of HTTP request. The format is string and the default is GET.
  • Path: Specifies the path of the HTTP request. The default is the root path (/). In this property, you can specify the query string, such as / index.html?page=12. If the property contains illegal characters (such as spaces), an error is thrown.
  • headers: an object that contains the header information of the HTTP request.
  • auth: a string representing HTTP basic authentication user:password.
  • Agent: controls the caching behavior. If the HTTP request uses agent, the default HTTP request is connection: keep alive. Its possible values are as follows:
    • undefined (default): for the current host and port, use the global Agent.
    • Agent: an object, the agent attribute will be passed in.
    • false: do not cache the connection. The default HTTP request is Connection: close.
  • keepAlive: a Boolean value indicating whether to reserve the socket for other future requests. The default value is false.
  • keepAliveMsecs: an integer. When keepalive is used, set how often to send a TCP KeepAlive packet so that the connection is not closed. The default value is 1000. This setting only makes sense when keepalive is set to true.
    The callback parameter of the request method is optional, triggered when a response event occurs, and only once.
    http.request() returns an instance of the http.ClientRequest class. It is a writable data stream. If you want to send a file through the POST method, you can write the file to the ClientRequest object.
    Here is an example of sending a POST request.
var postData = querystring.stringify({
  'msg' : 'Hello World!'
});

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': postData.length
  }
};

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(postData);
req.end();

Note that in the above code, req.end() must be called, even if no data is written in the request body. Because this means that the HTTP request has been completed.
Any errors in the sending process (DNS error, TCP error, HTTP resolution error) trigger an error event on the request object.

1.3 building HTTP server

SSL certificate is required to build HTTP server. For websites providing services to the public, SSL certificates need to be purchased from certification authorities; for websites for self use, they can be self-made.
OpenSSL is required for self-made SSL certificate. The specific commands are as follows.

openssl genrsa -out key.pem
openssl req -new -key key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
rm csr.pem

The above command generates two files: ert.pem (certificate file) and key.pem (private key file). With these two files, you can run the HTTP server.
Node.js provides an https module for processing encrypted access.

var https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

var a = https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);

The above code shows that the biggest difference between HTTP server and HTTP server is that the createServer method has one more options parameter. After running, you can test whether it can be accessed normally.

curl -k https://localhost:8000

Posted by JoeF on Sat, 26 Oct 2019 20:21:27 -0700