node.js web服务器案例

 2022/12/27学习笔记

1. 创建web服务器基本步骤

// 1. 导入http模块
const http = require('http');
// 2. 创建web服务器实例 http.createServer()方法
const server = http.createServer();
// 3. 为服务器实例绑定request事件,监听客户端请求   request是请求(客户端) response是响应(服务器)
server.on('request', function (request, response) {
    console.log('欢迎来到服务器');   // 如果有访问,控制台输出
    console.log(request.url);       // 客户端访问的服务器地址(index.html 首页html or / 根目录)
    console.log(request.method);    // 客户端请求的method类型(get or post)
    response.setHeader('Content-Type', 'text/html; charset=utf-8');     //设置响应头content-type解决中文乱码问题
    response.end('欢迎来到服务器')   // 向客户端响应一些内容
});
// 4. 启动服务器(默认80)
server.listen(80, function () {
    console.log('服务器运行于http://127.0.0.1');
})

2.动态响应内容

// 1. 导入http模块
const http = require('http');
// 2. 创建web服务器实例 http.createServer()方法
const server = http.createServer();
// 3. 为服务器实例绑定request事件,监听客户端请求
server.on('request', function (request, response) {
    const url = request.url
    let content = '404 页面不存在'
    // 判断客户端访问页面
    if (url === '/' || url === '/index.html') {
        content = '<h1>首页</h1>'
    } else if (url === '/about.html') {
        content = '<h1>关于</h1>'
    }
    // 设置响应头 防止中文乱码
    response.setHeader('Content-Type', 'text/html; charset=utf-8');
    // 向客户端响应内容
    response.end(content);
});
// 4. 启动服务器
server.listen(8080, function () {
    console.log('服务器运行于http://127.0.0.1:8080');
})

3.返回读取文件

// 导入http模块
const http = require('http');
// 导入fs模块
const fs = require('fs');
// 导入path模块
const path = require('path');
// 创建web服务器实例
const server = http.createServer();
// 为服务器实例绑定request事件,监听客户端请求
server.on('request', function (request, response) {
    const url = request.url
    // 设置文件路径
    const pathUrl = path.join(__dirname, '../../青柠起始页', url)
    // 打开文件内容
    fs.readFile(pathUrl, 'utf8', function (err, data) {
        if (err != null) {
            // 读取失败,返回错误页面不存在
            response.setHeader('Content-Type', 'text/html; charset=utf-8');
            response.end('404 页面不存在')
        } else {
            // 读取成功,将内容响应给客户端
            response.end(data)
        }
    });
})

// 启动服务器
server.listen(8080, function () {
    console.log('服务器运行于http://127.0.0.1:8080');
})

>>>效果<<<

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值