js中回调函数实现一个http服务器

不言
发布: 2018-07-25 10:30:21
原创
2096人浏览过

本篇文章分享给大家的内容是关于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头部信息
<img src="https://melovemingming-125387...;>
同样,火狐的也一样
<img src="https://melovemingming-125387...;>
先是请求头,后是请求体
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
登录后复制

此执行为异步执行,先执行到

腾讯智影-AI数字人
腾讯智影-AI数字人

基于AI数字人能力,实现7*24小时AI数字人直播带货,低成本实现直播业务快速增增,全天智能在线直播

腾讯智影-AI数字人 73
查看详情 腾讯智影-AI数字人
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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号