nodejs服务1

首先我们来看看浏览器访问网站的过程是怎么样的呢?
1.在浏览器地址栏中输入网址:
https://www.baidu.com
2.浏览器通过用户在地址栏中输入的url构建http请求
3.浏览器发起DNS解析请求,将域名转换为IP地址
4.浏览器将请求报文发送给服务器
5.服务器接收请求报文并解析
6.服务器处理用户的请求,并将处理的结果封装成http响应报文
7.服务器将 http 响应报文发送给浏览器
8.浏览器接收服务器响应的 http 报文,并解析
9.浏览器解析 html 界面展示(渲染), 在解析 html 页面时 遇到新的资源需要再次发起请求
10.最终浏览器展示出了 html 页面

nodejs创建服务

那么,怎么通过nodejs初步实现服务器功能呢?
我们一起来看看吧。

初步实现服务器功能

//初步实现服务器功能
const http=require("http");
//创建服务器实例对象
let server=http.createServer();
//绑定请求事件
server.on("request",(req,res)=>{
    res.end("ook");
});
//监听接口
server.listen(3000,()=>{
    console.log("running....")
});

但是如果这样子操作的话浏览器会出现无法访问的情况,这是因为没法通过localhost进行访问。

修改如下:
(上述写法可以简化)

初步实现静态资源

 const http = require("http");
    const path = require("path");
    const fs = require("fs");
    http.createServer((req,res)=>{
        if(req.url.startsWith("/index")){
            fs.readFile(path.join(__dirname,"www","index.html"),"utf8",(err,fileContent) =>{
                if(err){
                    res.end("server error");
                }else{
                    res.end(fileContent);
                }
            })
       
        }else if(req.url.startsWith("/about")){
            fs.readFile(path.join(__dirname,"www","about.html"),"utf8",(err,fileContent) =>{
                if(err){
                    res.end("server error");
                }else{
                    res.end(fileContent);
                }
            })
        }else{
            res.end("no connect");
        }
    }).listen(3000,()=>{
        console.log("running....")
    });

nodejs初步实现静态资源服务器的功能

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>
        欢迎来到我的页面
    </h1>
</body>
</html>

about.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>
        关于我们
    </h1>
</body>
</html>

index.html
about.html
考虑到后续的一致性,所以可以很容易的想到方法的封装。

let readfile = function (file,res) { 
    fs.readFile(path.join(__dirname, 'www', file), 'utf8', (err, fileContent) => { 
        if (err) { 
            res.end('Server Error');
        }
        res.end(fileContent);
    })
}
http.createServer((req, res) => { 
    // 判断客户端的url地址栏 
    if (req.url.startsWith('/index')) {
        // res.end('index');
        // write()  向客户端响应内容 可以写多次
        // res.write('Hello Index');
        // res.write('Hello Index  Index');
        // Day02/www/index.html
        // fs.readFile(path.join(__dirname, 'www', 'index.html'), 'utf8', (err, fileContent) => { 
        //     if (err) {
        //         res.end('server Error');
        //     } else { 
        //         res.end(fileContent);
        //     }

        // })
        readfile('index.html',res);
        // res.end(); 响应结束
    } else if (req.url.startsWith('/about')) {

        // 读取文件   www/about.html
        // fs.readFile(path.join(__dirname, 'www', 'about.html'), 'utf8', (err, fileContent) => { 
        //     if (err) { 
        //         res.end('Server Error');
        //     }
        //     res.end(fileContent);
        // })
        readfile('about.html',res);
        // res.end('about');  响应 页面  html
    } else { 
        res.end('no cONNECT');
    }

}).listen(3000, '192.168.0.123', () => {  //本机ip地址
    console.log('runnning.....');
})
// server.listen(3000);

响应完整的页面

const http = require("http");
const path = require("path");
const fs = require("fs");
http.createServer((req,res)=>{
        fs.readFile(path.join(__dirname,"www",req.url),"utf8",(err,fileContent) =>{
            if(err){
                //没找到对应文件
                res.writeHead(404,{
                    "content-Type":"text/plain;charest=utf8"
                });
                res.end("error,Dog")
            }else{
                res.end(fileContent);
            }
        })
}).listen(3000,()=>{
    console.log("running....");
})

测试页面显示的结果

显示图片的设置:
下载图片放置到当前的工作环境中→在浏览器中打开服务,直接在端口后面添加图片的名称→测试成功

模拟调试:
响应报文头中并没有标注当前文件类型怎么办?→考虑 在响应数据正常的情况下,标注所有的文件类型在响应报文头中
在这里插入图片描述

什么是mime.josn文件?
对应文件的响应报文头格式。

在代码中加载 以上模块 mime.json 模块
在这里插入图片描述
在这里插入图片描述

nodejs实现静态服务器的功能:
将以上服务器端的响应进行封装如下:
在这里插入图片描述
引入模块: 不需要 http 模块

在这里插入图片描述
新建一个js文件进行测试服务,代码如下:
代码中的www为静态资源的目录

在这里插入图片描述

以上的代码,就是实现静态资源服务的功能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值