preface

Net and HTTP modules are one of the core modules of Node. They can build their own servers and clients to respond to and send requests.

Net module server/client

The NET module written here is a TCP based server and client, using a simple request and response demo of net.createserver and Net.Connect.

Var net = require('net')
var sever=net.createServer(function(connection){// Client closes the connection execution event connection.on('end'.function(){
    //   console.log('Client closes connection')
  })
  connection.on('data'.function(data){
    console.log('Server: received data sent by client as'+ data.tostring ())}) // Write the data to the client.'response hello')
})
sever.listen(8080,function(){
    // console.log('Listening port')})Copy the code
Var net = require('net')
var client = net.connect({port:8080},function(){
    // console.log("Connect to the server"}) // The client receives the event executed by the server client.on('data'.function(data){
    console.log('Client: received server response data as'+data.toString()) client.end()}) // Data passed to the server client.write('hello')
client.on('end'.function(){
    // console.log('Disconnect from the server')})Copy the code

The results

The HTTP module has four request types

HTTP server:

Http.createserver creates an instance of http.Server that uses a function as an HTTP request handler. This function takes two parameters: the request object (REq) processes some information about the request and the response object (RES) processes the data about the response.

// HTTP server const HTTP = require("http");
var fs = require("fs");
var url = require('url')

http.createServer(function(req, res) { var urlPath = url.parse(req.url); Var meth = req.method // urlpath. pathName Specifies the path part of the URL that is obtained and set. // Meth Specifies the method used to obtain request dataif (urlPath.pathname === '/' && meth === 'GET') {
        res.write(' get ok');
    } else if (urlPath.pathname === '/users' && meth === 'POST') {
        res.writeHead(200, {
            'content-type': 'text/html; charset=utf-8'
        });
        fs.readFile('user.json'.function (err, data) {
            if (err) {
                returnconsole.error(err); } var data = data.toString(); // Return data res.write(data); }); }else if (urlPath.pathname === '/list' && meth === 'PUT') {
        res.write('put ok');
    } else if (urlPath.pathname === '/detail' && meth === 'DELETE') {
        res.write(' delete ok');
    } else {
        res.writeHead(404, {
            'content-type': 'text/html; charset=utf-8'
        });
        res.write('404')
    }
    res.on('data'.function (data) {
        console.log(data.toString())
    })

}).listen(3000, function () {
    console.log("server start 3000");
});

Copy the code

HTTP client:

The HTTP module provides two methods to create an HTTP client, http.request and http.get, to make a request to the HTTP server. HTTP. Get is a shortcut for HTTP. Request, which supports only get requests.

The http.request(options,callback) method initiates an HTTP request. Option is the parameter of the request, and callback is the callback function of the request. Process the returned data. Options Common parameters are as follows: 1) host: specifies the domain name or IP address of the requested website. 2) port: the port for requesting the website. The default is 80. 3) method: request method, default is GET. 4) Path: the requested path relative to the root, default is “/”. The request parameters should be included. 5) Headers: the content of the request header.

The crawler implemented by NodeJS can actually use the client created by THE HTTP module to send a request to the address where we want to grab data, and get the response data for parsing.

get

// HTTP client const HTTP = require("http"); // The configuration to send requestslet config = {
    host: "localhost",
    port: 3000,
    path:'/',
    method: "GET", headers: { a: 1 } }; // Create a clientlet client = http.request(config, function(res) {// Receive the data returned by the serverlet repData=' ';
    res.on("data".function(data) {
        repData=data.toString()
        console.log(repData)
    });
    res.on("end".function() { // console.log(Buffer.concat(arr).toString()); }); }); // Send the request client.end(); End the request or the server will not receive the messageCopy the code

The client initiates an HTTP request. The request method is GET. The server receives the GET request, and the matching path is the home page.

post

Var HTTP = require('http');
var querystring = require("querystring");
var contents = querystring.stringify({
    name: "Alasti",
    email: "[email protected]",
    address: " chengdu"}); var options = { host:"localhost",
    port: 3000,
    path:"/users",
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"."Content-Length": contents.length
    }
};
var req = http.request(options, function (res) {
    res.setEncoding("utf8");
    res.on("data".function(data) { console.log(data); }) }) req.write(contents); // End the request, otherwise the server will not receive the message req.end(); // The response data is {"user1" : {
       "name" : "mahesh"."password" : "password1"."profession" : "teacher"."id": 1}."user2" : {
       "name" : "suresh"."password" : "password2"."profession" : "librarian"."id": 2}}Copy the code

The client initiates an HTTP request. The request method is POST, and post passes the data in the matching path/Users. The server responds to the request and returns the contents of the data user.json.

put

// HTTP client const HTTP = require("http"); // The configuration to send requestslet config = {
    host: "localhost",
    port: 3000,
    path:"/list",
    method: "put", headers: { a: 1 } }; // Create a clientlet client = http.request(config, function(res) {// Receive the data returned by the serverlet repData=' ';
    res.on("data".function(data) {
        repData=data.toString()
        console.log(repData)
    });
    res.on("end".function() { // console.log(Buffer.concat(arr).toString()); }); }); // Send the request client.end();Copy the code

The client initiates an HTTP request with the put method. The server receives the PUT request with the matching path /list. The response data is put OK

delect

Var HTTP = require('http');
var querystring = require("querystring");
var contents = querystring.stringify({
    name: "Alasti",
    email: "[email protected]",
    address: " chengdu"}); var options = { host:"localhost",
    port: 3000,
    path:'/detail',
    method: "DELETE",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"."Content-Length": contents.length
    }
};
var req = http.request(options, function (res) {
    res.setEncoding("utf8");
    res.on("data".function (data) {
        console.log(data);
    })
})

req.write(contents);
req.end();
Copy the code

The server receives the DELETE request with the matching path of /detail and responds with delete OK