Node.js HTTP module

Built-in HTTP module

HTTP is a built-in module in Node.js that allows Node.js to transfer data via Hypertext Transfer Protocol (HTTP).

If you want to use an HTTP module, you need to first introduce the HTTP module through the require() method, as follows:

var http = require('http');

Creating a simple server

The HTTP module in Node.js creates an HTTP server that listens on the server port and returns the response to the client.

Example:

Use the createServer() method to create an HTTP server, as follows:

var http = require('http');
http.createServer(function (req, res) {
  res.write('Hello xkd'); 
  res.end(); 
}).listen(8888); 

Launch the Node.js file (your custom file name) in the command tool, open the browser, access http://127.0.0.1:8888/ You can see "Hello xkd" displayed in the browser page, such as the simplest server successfully built.

The HTTP module in Node.js encapsulates an HTTP server and a simple HTTP client, http.Server is an event-based HTTP server, and http.request is an HTTP client tool for making requests to HTTP servers.The two parameters req and res in the createServer() method represent the request object and the response object, respectively.Where req is an instance of http.IncomingMessage and res is an instance of http.ServerResponse.

HTTP Server

In addition to using the createServer() method to return an http.Server object to create a server, we can also use the following methods.

Example:

Create an http.Server object and add request event listening to it:

var http = require("http");
var server = new http.Server();

server.on("request",function(req,res){
    res.writeHead(200,{        
      "content-type":"text/plain; charset=utf-8"
    });
    res.write("xkd");
    res.end();
});
server.listen(8888);
Events for http.Server

Http.Server is an event-based server that inherits from EventEmitter.The events provided by http.Server are as follows:

  • Request: When a client request arrives, the event is triggered, providing two parameters, req and res, representing the request and response information, which is the most common event.

  • Connection: When a TCP connection is established, this event is triggered, providing a parameter socket, which is an instance of net.Socket.

  • close: Triggers an event when the server shuts down (note that it is not when the user disconnects).

HTTP Client

The HTTP module provides two functions, http.request and http.get, that make requests to HTTP servers as clients.

http.request(option,callback)

The http.request() method accepts two parameters, where the parameter option is an object similar to an associated array that represents the requested parameter.The callback is the callback function of the request and needs to pass a parameter.

Example:

var http=require('http');
var querystring=require('querystring');
//Start Services
http.createServer(function(req,res){
	console.log('Start the request, parse the parameters');
	//Resolve post request
	var post='';
	req.on('data',function(chunk){
		post+=chunk;
	});
	req.on('end',function(){
		post=querystring.parse(post);
		//Parsing complete
		console.log('Parameter parsing complete, return name parameter');
		res.end(post.name);
	});
}).listen(8888);
 
 
//client request
var contents=querystring.stringify({
	name:'Tom',
	age:18,
	city:'beijing'
});

//Declare Request Parameters
var options={
	host:'localhost',
	path:'/',
	port:8888,
	method:'POST',
	headers:{
		'Content-Type':'application/x-www-form-urlencoded',
		'Content-Length':contents.length
	}
};
//Send Request
var req=http.request(options,function(res){
	res.setEncoding('utf-8');
	res.on('data',function(data){
		console.log('Background return data');
		console.log('name The value of the parameter is:' + data);
	})
});
req.write(contents);
//end() must be called
req.end();

Then start the Node.js file, which outputs the following:

> node file.js
 Start the request, parse the parameters
 Parameter parsing complete, return name parameter
 Background return data
 The value of the name parameter is Tom
http.get(option,callback)

The http.get() method is a simplified version of the http.request method, except that http.get automatically sets the request method to a GET request without manually calling req.end().If we do not call the end method when using the http.request method, the server will not receive the information.

Example:
var http=require('http');
var url=require('url');
var util=require('util');
//Start Services
http.createServer(function(req,res){
	console.log('Start the request, parse the parameters');
	var params=url.parse(req.url,true);
	console.log('Parsing complete');
	console.log(util.inspect(params));
	console.log('Return to Client name');
	res.end(params.query.name);
}).listen(8888);
 
//client request
var request=http.get({
	host:'localhost',
	path:'/user?name=Tom&age=18&city=beijing',
	port:8888},function(res){
	res.setEncoding('utf-8');
	res.on('data',function(data){
		console.log('Server side corresponding name Values are:'+data);
	})
});

Then start the Node.js file, which outputs the following:

>node file.js
//Start the request, parse the parameters
//Parsing complete
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?name=Tom&age=18&city=beijing',
  query: { name: 'Tom', age: '18', city: 'beijing' },
  pathname: '/user',
  path: '/user?name=Tom&age=18&city=beijing',
  href: '/user?name=Tom&age=18&city=beijing' }
//Return name to client
//The corresponding name value on the server side is Tom

More to see: https://www.9xkd.com/3716132715.html

Tags: Programming socket

Posted on Thu, 16 Apr 2020 19:58:25 -0700 by weknowtheworld