nodejs -实现静态网站

  • 目录
    • 实现静态网站功能
      • 使用http模块初步实现服务器功能
      • 处理请求路径的分发
      • 响应完整的页面信息
    • 参数传递与获取
      • get参数处理 -url核心模块
      • get参数解析
      • post参数处理 -querystring
    • 登陆验证功能

实现静态网站功能

  • 使用http模块初步实现服务器功能
const http = require('http');
--------------------------------------------
// 创建服务器实例对象
let server = http.createServer();
// 绑定请求事件
server.on('request', (req, res) => {
    res.end('hello');
});
// 监听端口
server.listen(3000);
---------------------------------------------
http.createServer((req,res)=>{
    res.end('ok')
}).listen(3000,'192.168.1.8',()=>{
    console.log('running...');
});
  • 处理请求路径的分发
    1、req对象是Class: http.IncomingMessage的实例对象
    2、res对象是Class: http.ServerResponse的实例对象
const http = require('http');

http.createServer((req, res) => {
    // req.url可以获取URL中的路径(端口之后部分)
    // res.end(req.url);
    if (req.url.startsWith('/index')) {
        // write向客户端响应内容,可以写多次
        res.write('hello');
        res.write('index');
        // end方法用来完成响应,只能执行一次
        res.end();
    } else if (req.url.startsWith('/about')) {
        res.end('about');
    } else {
        res.end('no content');
    }
}).listen(3000, () => {
    console.log('running...');
});
  • 响应完整的页面信息
    请求+路径分发+文件读取+响应返回
const http = require('http');
const path = require('path');
const fs = require('fs');

// 根据路径读取文件的内容,并且响应到浏览器端
let readFile = (url, res) => {
    fs.readFile(path.join(__dirname, 'www', url), 'utf8', (err, fileContent) => {
        if (err) {
            res.end('server error');
        } else {
            res.end(fileContent);
        }
    });
}

http.createServer((req, res) => {
    // 处理路径的分发
    if (req.url.startsWith('/index')) {
        readFile('index.html', res);
    } else if (req.url.startsWith('/about')) {
        readFile('about.html', res);
    } else if (req.url.startsWith('/list')) {
        readFile('list.html', res);
    } else {
        // 设置相应类型和编码
        res.writeHead(200, {
            'Content-Type': 'text/plain;charset=utf8'
        });
        res.end('页面被叼走了');
    }
}).listen(3000, () => {
    console.log('running...');
});
----------------------------------------------------
const http = require('http');
const path = require('path');
const fs = require('fs');
const mime = require('./mime.json');

http.createServer((req, res) => {
    fs.readFile(path.join(__dirname, 'www', req.url), (err, fileContent) => {
        if (err) {
            // 没有找到对应文件
            res.writeHead(404, {
                'Content-Type': 'text/plain; charset=utf8'
            });
            res.end('页面被叼走了');
        } else {
            let dtype = 'text/html';
            // 获取请求文件的后缀
            let ext = path.extname(req.url);
            // 如果请求的文件后缀合理,就获取到标准的响应格式
            if (mime[ext]) {
                dtype = mime[ext];
            }
            // 如果响应的内容是文本,就设置成utf8编码
            if (dtype.startsWith('text')) {
                dtype += '; charset=utf8'
            }
            // 设置响应头信息
            res.writeHead(200, {
                'Content-Type': dtype
            });
            res.end(fileContent);
        }
    });
}).listen(3000, () => {
    console.log('running...');
});

参数传递与获取(get,post)

  • get参数处理-url核心模块
const url = require('url');

// parse方法的作用就是把URL字符串转化为对象
let str = 'http://www.baidu.com/abc/qqq?flag=123&keyword=java';
let ret = url.parse(str,true);
console.log(ret.query.keyword);
----------------------------------------------------------
let obj = {
  protocol: 'http:',
  slashes: true,  // 有 ‘//:’ 为true
  auth: null,
  host: 'www.baidu.com',  //包括端口
  port: null,
  hostname: 'www.baidu.com',  //不包括端口
  hash: null,  // #后面的部分
  search: '?flag=123&keyword=java',
  query: 'flag=123&keyword=java',
  pathname: '/abc/qqq',  // 路径 域名后至?前
  path: '/abc/qqq?flag=123&keyword=java',
  href: 'http://www.baidu.com/abc/qqq?flag=123&keyword=java' 
};
// format的作用就是把对象转化为标准的URL字符串
let ret = url.format(obj);
console.log(ret);
  • get 参数解析
const http = require('http');
const path = require('path');
const url = require('url');

http.createServer((req,res)=>{
    let obj = url.parse(req.url,true);
    res.end(obj.query.username + '=========' + obj.query.password);
}).listen(3000,()=>{
    console.log('running....');
})
  • post参数处理
const querystring = require('querystring');
const http = require('http');

let param1 = 'username=lisi&password=123';
let param2 = 'foo=bar&abc=xyz&abc=123';
// parse方法的作用就是把字符串转成对象
let obj = querystring.parse(param2);
console.log(obj);
----------------------------------------------------------
let obj1 = {
    flag: '123',
    abc: ['hello', 'hi']
}
// stringify的作用就是把对象转成字符串
let str1 = querystring.stringify(obj1);
console.log(str1);
----------------------------------------------------------
http.createServer((req, res) => {
    if (req.url.startsWith('/login')) {
        let pdata = '';
        req.on('data', (chunk) => {
            // 每次获取一部分数据
            pdata += chunk;
        });
        req.on('end', () => {
            // 这里才能得到完整的数据
            console.log(pdata);
            let obj = querystring.parse(pdata);
            res.end(obj.username + '-----' + obj.password);
        });
    }
}).listen(3000, () => {
    console.log('running...');
})

登陆验证功能

const http = require('http');
const url = require('url');
const querystring = require('querystring');
const ss = require('./ss.js');

http.createServer((req, res) => {
    // 启动静态资源服务
    if (req.url.startsWith('/www')) {
        ss.staticServer(req, res, __dirname);
    }
    console.log(req.url);
    // 动态资源
    if (req.url.startsWith('/login')) {
        // get请求
        if (req.method == 'GET') {
            let param = url.parse(req.url, true).query;
            if (param.username == 'admin' && param.password == '123') {
                res.end('get success');
            } else {
                res.end('get failure');
            }
        }
        // post请求
        if (req.method == 'POST') {
            let pdata = '';
            req.on('data', (chunk) => {
                pdata += chunk;
            });
            req.on('end', () => {
                let obj = querystring.parse(pdata);
                if (obj.username == 'admin' && obj.password == '123') {
                    res.end('post success');
                } else {
                    res.end('post failure');
                }
            });
        }
    }
}).listen(3000, () => {
    console.log('running....');
});
  • ss.js
const path = require('path');
const fs = require('fs');
const mime = require('./mime.json');

exports.staticServer = (req, res, root) => {
    fs.readFile(path.join(root, req.url), (err, fileContent) => {
        if (err) {
            // 没有找到对应文件
            res.writeHead(404, {
                'Content-Type': 'text/plain; charset=utf8'
            });
            res.end('页面被狗狗叼走了');
        } else {
            let dtype = 'text/html';
            // 获取请求文件的后缀
            let ext = path.extname(req.url);
            // 如果请求的文件后缀合理,就获取到标准的响应格式
            if (mime[ext]) {
                dtype = mime[ext];
            }
            // 如果响应的内容是文本,就设置成utf8编码
            if (dtype.startsWith('text')) {
                dtype += '; charset=utf8'
            }
            // 设置响应头信息
            res.writeHead(200, {
                'Content-Type': dtype
            });
            res.end(fileContent);
        }
    });
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容