JS callback function implementation of an HTTP server

Source: Internet
Author: User
Tags webp
The content of this article is about JS in the callback function to implement an HTTP server, the content is very detailed, next we will look at the specific content, hope can help everyone.

Network operation

First, use the HTTP module to implement an HTTP server

var http = require (' http ');    Using the HTTP Module http.createserver (        function (request, response) {            Response.writehead ($, {' Content-type ': ') Text-plain '});    HTTP response Header            response.end (' Hello word\n ');    The content returned        }    ). Listen (8124);    Listening on port 8124
PS c:\users\mingm\desktop\test> Node Main.js

Access http://127.0.0.1:8124/return Hello Word

Some API

HTTP Module

Two ways,

    1. When used as a server side, creates an HTTP server, listens for HTTP client requests, and returns a response.

    2. When used as a client, initiates an HTTP client request to obtain a server-side response

The server side is driven by events, and the callback function is called once when the server is created, that is, event-driven

HTTP request Header

HTTP requests are essentially data streams, consisting of the request header and the request body.
Open the Browser developer tool, select the network panel, then, refresh the page, again, select a file, in the Headers window, display the HTTP header information of the current file request

Similarly, Firefox is the same

First the request header, then the request body
When an HTTP request is sent to the server, it is transmitted from one byte to the next, and the HTTP server created by the HTTP module makes a callback function after it receives the complete request header.

var http = require (' http ');    Use HTTP Module http.createserver (        function (request, response) {            var body = [];            Console.log (Request.method);            Console.log ("--------------");            Console.log (request.headers);            Console.log ("---------------");        }    ). Listen (8124);    Listening on port 8124
PS c:\users\mingm\desktop\test> node Main.jsget--------------{host: ' 127.0.0.1:8124 ',  connection: ' Keep-alive ',  ' cache-control ': ' max-age=0 ',  ' upgrade-insecure-requests ': ' 1 ',  dnt: ' 1 ',  ' User-agent ':   ' mozilla/5.0 (Windows NT 10.0; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/67.0.3396.99 safari/537.36 ',  Accept:   ' text/html, application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 ',  ' accept-encoding ': ' gzip, Deflate, BR ',  ' accept-language ': ' zh-cn,zh;q=0.9 '}---------------

callback function

var fs = require ("FS"); Fs.readfile (' Input.txt ', function (err, data) {    Console.log ("3333");    Console.log (err);    Console.log (Data.tostring ());    Console.log ("3333");}); Console.log ("program execution ends!");
PS c:\users\mingm\desktop\test> node Main.js program execution End!3333null333333333333333333333333333333ps C:\Users\mingm\ Desktop\test>

When an I/O operation is encountered, the execution is skipped before the current content is executed. So the result is then passed to the last function of the argument list for the result of the execution, so the last function is the callback

HTTP callback function, request

var http = require (' http '); Http.createserver (    function (request, response) {        var body = [];        Console.log (Request.method);        Console.log (request.headers);    Console.log (1111111111);    Console.log (body);       Request.on (' End ', function () {        BODY = buffer.concat (body);        Console.log (222222222222222);        Console.log (Body.tostring ());    });    Console.log (4444444444444);    Response.writehead ($, {' Content-type ': ' Text-plain '});    Response.End (' Hello word\n ');    Console.log (55555555555);    }). Listen (8124);

Execution results

PS c:\users\mingm\desktop\test> node main.jsget{host: ' 127.0.0.1:8124 ', Connection: ' keep-alive ', ' Cache-control ': ' Max-age=0 ', ' upgrade-insecure-requests ': ' 1 ', ' user-agent ': ' mozilla/5.0 (Windows NT 10.0; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/67.0.3396.99 safari/537.36 ', dnt: ' 1 ', accept: ' Text/html,applicati on/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 ', ' accept-encoding ': ' gzip, deflate, BR ', ' Accept-language ': ' zh-cn,zh;q=0.9 '}1111111111[]444444444444455555555555222222222222222get{host: ' 127.0.0.1:8124 ' , connection: ' keep-alive ', pragma: ' No-cache ', ' cache-control ': ' No-cache ', ' user-agent ': ' mozilla/5.0 (Windows NT 10.0; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/67.0.3396.99 safari/537.36 ', dnt: ' 1 ', accept: ' Image/webp,image/apng , image/*,*/*;q=0.8 ', Referer: ' http://127.0.0.1:8124/', ' accept-encoding ': ' gzip, deflate, BR ', ' accept-language ': ' ZH -cn,zh;q=0.9 '}1111111111[]444444444444455555555555222222222222222 

This execution is performed asynchronously, first to

Console.log (body);

Because Request.on needs to wait for return, the following statement is executed asynchronously

Console.log (444);

It then returns the content, executes the Request.on, notifies the result back to the last parameter of the function, and executes.

HTTP response

The service side returns the requested body of the client as is, back to the client

PS c:\users\mingm\desktop\test> Node main.js4444444444442222222233333333555555
var http = require ("http"); Http.createserver (function (request, response) {    console.log (444444444444);    Response.writehead ($, {' Content-type ': ' Text/plain '});                    For the response header, the original route is sent to                    the client Request.on (                        "data",                         function (chunk) {                            Response.Write (chunk);                            Console.log (111111);                    });                    Console.log (22222222);                    Request.on (' End ', function () {response.end (); Console.log (555555)});                    Console.log (33333333);                }). Listen (8124);

It's a little messy.

HTTP Client

Node sends an HTTP client request

var options = {    hostname: ' Www.iming.info ',    port:80,    //Port    : '/upload ',    //requested path    Method: ' Post ',        //Request Methods for Post method    headers: {        ' content-type ': ' application/x-www-form-urlencoded '    // Header information    },}var http = require (' http '); var request = http.request (options, function (response) {}); Request.write (' Hello word! '); Request.end ();

The above sends an HTTP request.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.