利用nodejs实现成绩查询的功能

http(HTTP)简述

Node.js 中的 HTTP 接口旨在支持许多传统上难以使用的协议的特性。 特别是,大块的(且可能是块编码的)消息。 接口永远不会缓冲整个请求或响应,所以用户可以流式地传输数据。如果要是用这个模块,只需要引入即可:

const http = require('http');

1.创建服务端的请求和响应

http.createServer([options][, requestListener]):返回新的 http.Server 实例。requestListener是一个函数,会被自动添加到 ‘request’ 事件。

http.createServer((req,res)=>{
    
}).listen(3000,()=>{
    console.log('running...');
})

此时请求已经发送,并且在本地创建了一个端口,可以在浏览器网址栏中输入 localhost:3000进行查看,但是没有任何响应,是因为箭头函数中没有写入内容,我们可以通过request.end([data[, encoding]][, callback])方法来完成发送请求,服务器已经成功相应,输入端口后,页面出现内容

const http = require('http');

http.createServer((req,res)=>{
    res.end('Hello');
}).listen(3000,()=>{
    console.log('running...');
})

在这里插入图片描述

2.新建成绩表单以及显示结果的页面

查询成绩的入口地址 /query

获取成绩的结果 /score

<!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>
    <form action="" method="POST">
        请输入考号:<input type="text" name="code"/>
        <input type="submit" value="查询">
    </form>
</body>
</html>

在这里插入图片描述
我们输入考号点击查询时,要把输入的考号传递给后台,再根据考号查询对应的成绩,所以我们怎么将数据提交给后台呢?
其实很简单,我们只需要改变form的action属性值就可以啦!
此例中,改为:

    <form action="http://localhost:3000/score">

最后将文件扩展名改为.tpl即可

如果使用vscode软件,将html文件改为tpl文件时,可能会出现问题,我们可以在扩展里面搜索ext:tpl 下载相应的插件之后,我们就可以用tpl文件了

接下来,继续新建一个可以显示成绩的html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩结果</title>
</head>
<body>
    <div>
        <ul>
            <li>语文: $$chinses$$</li>
            <li>数学: $$math$$</li>
            <li>外语: $$english$$</li>
            <li>综合: $$summary$$</li>
        </ul>
    </div>
</body>
</html>

最后创建一个.json文件用于存放成绩

{
    "no123":{
        "chinses":"110",
        "math":"140",
        "english":"129",
        "summary":"239"
    },
    "no124":{
        "chinses":"100",
        "math":"140",
        "english":"129",
        "summary":"239"
    }
    ...
}

3.设置路由(规划路径)

const http = require('http')
const fs = require('fs');
http.createServer((req,res)=>{
    console.log(req);
    // 路由(请求路径+请求的方式)
    if (req.url.startsWith('/query') && req.method == 'GET') {
        // console.log('请求了对应的路由地址 query');
       res.writeHead(200,{
           'Content-Type':'text/plain;charset=utf8'
        })
        res.end('请求了query路径地址'); 
    }
}).listen(3000,()=>{
    console.log('running...');
     
})

此时服务器正常启动
在这里插入图片描述
在浏览器网址中输入http://localhost:3000/query
在这里插入图片描述

我们可以看到会出现服务端响应的结果内容,但是内容是乱码,解决办法就是修改响应头

       res.writeHead(200,{
           'Content-Type':'text/plain;charset=utf8'
        })

现在就好啦!!!
在这里插入图片描述
接着继续添加一种方式去查询成绩

        fs.readFile(path.join(__dirname, 'view', 'index.tpl'), (err, content) => {
            if (err) {
                console.log('===========');
                res.writeHead(500, {
                    'Content-Type': 'text/plain;charset=utf8'
                });
                res.end('服务器错误,请与管理员来联系')
            }
            res.end(content)
        })

content就是index.tpl表单文件里面的内容,此时结果如下:
在这里插入图片描述
然后,继续添加响应的结果判断

else if (req.url.startsWith('/score') && req.method == 'POST') { 
		res.writeHead(500, {
            'Content-Type': 'text/plain;charset=utf8'
        });
        // 获取成绩的结果  /score
        let pdata = '';
        // 请求数据时 触发的事件data
        // 将 post请求 传递过来的数据 使用变量 pdata接受
        req.on('data', (chunk) => {
            pdata += chunk;
        });
        // 请求数据结束时 触发的事件
        req.on('end',()=> {
             console.log('================='+pdata);
        })
        res.end('请求结束'+pdata);
    }

查看服务端的响应:
在这里插入图片描述
输入学号,点击查询后,浏览器会自动跳转至http://localhost:3000/score
在这里插入图片描述
(解决乱码的方式和上面的一样)
在这里插入图片描述
我们发现,服务端最终获取的结果是字符串(code=no123),而我们所需要的是code所对应的值,所以将获取的字符串转化成对象
在这里插入图片描述

//通过这个模块调用其中的方法来将字符串转化为对象
const queryString = require('querystring');
 // 将字符串类型的数据 转换为 对象类型
let obj = queryString.parse(pdata);

最后调用前面的.json文件

const scoreData = require('./data.json');
let result = scoreData[obj.code];
console.log(result);
// 将返回的结果 result   写在  页面中
// 要想写在页面 就得通过fs文件系统 读取 result.tpl模板文件
fs.readFile(path.join(__dirname, 'view', 'result.tpl'), (err, content) => { 
      // console.log(content);   buffer类型
          if (err) {
            res.writeHead(500, {
              'Content-Type': 'text/plain;charset=utf8'
            });
           res.end('服务器错误,请与管理员来联系')
          }
// 因为replace() 方法 只有字符串有  所以要将buffer转换为字符串
         content = content.toString();
         content = content.replace('$$chinses$$', result.chinses);
         content = content.replace('$$chinses$$', result.chinses);
         content = content.replace('$$math$$', result.math);
         content = content.replace('$$english$$', result.english);
         content = content.replace('$$summary$$', result.summary);
         res.end(content)
})

最终结果如图所示:
在这里插入图片描述

完整代码

// 创建后台 就是服务器的功能
const http = require('http')
const fs = require('fs');
const path = require('path');
const queryString = require('querystring');
const scoreData = require('./data.json');
http.createServer((req,res)=>{
    // 路由(请求路径+请求的方式)
    if (req.url.startsWith('/query') && req.method == 'GET') {

        fs.readFile(path.join(__dirname, 'view', 'index.tpl'), (err, content) => {
            res.end(content)
        })

    }else if (req.url.startsWith('/score') && req.method == 'POST') { 
        // 获取成绩的结果  /score
        let pdata = '';
        // 请求数据时 触发的事件data
        // 将 post请求 传递过来的数据 使用变量 pdata接受
        req.on('data', (chunk) => {
            pdata += chunk;
        });
        // 请求数据结束时 触发的事件
        req.on('end',()=> {
             // 将字符串类型的数据 转换为 对象类型
            let obj = queryString.parse(pdata);
            // console.log(obj);  {code:'no123'}
            // 将 obj对象下code属性 获取到code对应的值
            let result = scoreData[obj.code];
            console.log(result);
            // 将返回的结果 result   写在  页面中
            // 要想写在页面 就得通过fs文件系统 读取 result.tpl模板文件
            fs.readFile(path.join(__dirname, 'view', 'result.tpl'), (err, content) => { 
                // console.log(content);   buffer类型
                if (err) {
                    res.writeHead(500, {
                        'Content-Type': 'text/plain;charset=utf8'
                    });
                    res.end('服务器错误,请与管理员来联系')
                }
                // 因为replace() 方法 只有字符串有  所以 要将buffer转换为字符串
                content = content.toString();
                content= content.replace('$$chinses$$', result.chinses);
                content = content.replace('$$chinses$$', result.chinses);
                content = content.replace('$$math$$', result.math);
                content = content.replace('$$english$$', result.english);
                content = content.replace('$$summary$$', result.summary);
                res.end(content)
    
            })
        })
    }
}).listen(3000,()=>{
    console.log('running...');
     
})

在这里插入图片描述

基础回顾—静态资源服务器

静态资源服务器功能

总结

浏览器 访问网站的过程:

  1. 浏览器地址栏中输入地址
  2. 浏览器通过用户在地址栏中输入的url构建https请求
  3. 浏览器发起DNS解析请求, 将域名转换为 IP地址
  4. 浏览器将请求的报文头,发送给服务器
  5. 服务器接收到请求报文头并解析
  6. 服务器处理用户请求 并将处理的结果封装成http响应
  7. 服务器将 http响应报文头发送给浏览器
  8. 浏览器接收到服务器 响应的http报文并解析
  9. 浏览器解析html界面展示(渲染)在解析html界面是 遇到新的资源需要再发送请求
  10. 最终浏览器展示html界面
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值