首頁  >  文章  >  後端開發  >  js中回呼函數實作一個http伺服器

js中回呼函數實作一個http伺服器

不言
不言原創
2018-07-25 10:30:211793瀏覽

這篇文章分享給大家的內容是關於js中回呼函數實作一個http伺服器,內容很詳細,接下來我們就來看看具體的內容,希望可以幫助到大家。

網路操作

首先使用http模組實作一個http伺服器

var http = require('http');    // 使用http模块

http.createServer (
        function (request, response) {
            response.writeHead(200, {'Content-Type': 'text-plain'});    // http响应头部
            response.end('hello word\n');    // 返回的内容
        }
    ).listen(8124);    // 监听8124端口
PS C:\Users\mingm\Desktop\test> node main.js

存取http://127.0.0.1: 8124/ 回傳hello word

一些api

#http模組

兩種方式,

  1. 作為伺服器端使用的時,建立一個http伺服器,監聽http客戶端請求,並回傳回應。

  2. 作為客戶端使用的時候,發起http客戶端請求,用來獲得伺服器端的回應

伺服器端的是以事件為驅動的,建立伺服器時的回呼函數就會被呼叫一次,即,這是事件驅動

http請求頭

http的請求本質是資料流,由請求頭和請求體組成。
開啟瀏覽器的開發者工具,選擇network面板,然後,刷新頁面,再次,選擇一個文件,在headers視窗中,顯示出當前文件請求的http頭部資訊

先是請求頭,後是請求體
http請求發送給伺服器時,是從頭到尾一個一個位元組以資料流的方式發送,http模組創建的http伺服器在接收到完整的請求頭以後,進行回調函數,

var http = require('http');    // 使用http模块

http.createServer (
        function (request, response) {
            var body = [];

            console.log(request.method);
            console.log("--------------");
            console.log(request.headers);
            console.log("---------------");
        }
    ).listen(8124);    // 监听8124端口
PS C:\Users\mingm\Desktop\test> node main.js
GET
--------------
{ 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' }
---------------

回呼函數

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("程序执行结束!");
PS C:\Users\mingm\Desktop\test> node main.js
程序执行结束!
3333
null
33333333333333333333333333
3333
PS C:\Users\mingm\Desktop\test>

當遇到需要i/o操作的時候,先跳過執行,在執行目前的內容。所以結果為此,然後在將執行完成的結果傳給參數列表的最後一個函數,所以最後一個函數為回調

http的回調函數,請求

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(200, {'Content-Type': 'text-plain'});
    response.end('hello word\n');
    console.log(55555555555);
    }
).listen(8124);

執行結果

PS C:\Users\mingm\Desktop\test> node main.js
GET
{ 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,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' }
1111111111
[]
4444444444444
55555555555
222222222222222

GET
{ 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
[]
4444444444444
55555555555
222222222222222

此執行為非同步執行,先執行到

console.log(body);

由於request.on需要等待返回,所以非同步執行下方的語句

console.log(444);

接著返回內容,再執行request. on,將結果通知回到函數的最後一個參數,然後執行完畢。

http回應

服務端原樣將客戶端請求的請求體,傳回給客戶端

PS C:\Users\mingm\Desktop\test> node main.js
444444444444
22222222
33333333
555555
var http = require("http");

http.createServer(function (request, response){
    console.log(444444444444);
    response.writeHead(200, { 'Content-Type': 'text/plain' });

                    // 为响应头,即原路发送给客户端
                    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);

寫的有點亂

http客戶端

node發送一個http客戶端請求

var options = {
    hostname: 'www.iming.info',
    port: 80,    // 端口为80
    path: '/upload',    // 请求的路径
    method: 'POST',        // 请求的方法为post方法
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'    // 头部信息
    },
}

var http = require('http');

var request = http.request(options, function (response) {});

request.write('hello word!');
request.end();

以上發送了一個http請求。

相關推薦:

axios原始碼解析如何實作一個HTTP請求庫

以上是js中回呼函數實作一個http伺服器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn