http模块搭建一个服务器

// 引入node内置的http模块,来进行http的服务器开发
const http = require('http');
// 引入node内置的fs模块,来完成对应文件系统(硬盘里面的文件)进行操作
const fs = require('fs');

// 创建一个http的服务器
const server = http.createServer((request, response) => {
    // 如果url与资源都映射,我们通过代码一个个的去写,是基本不可能的,
    // 所以,我们就定义一个url的规则,满足这个规则的url,我们就去执行的目录中匹配;
    let url = request.url;
    let content = '';
    if (url.startsWith('/test')) {
    	try {
			// __dirname : node 中的内置变量,返回当前文件的绝对路径
	        url = url.replace(/^\/test/g, '/static');
	        content = fs.readFileSync(__dirname + url);
	        // 可根据不同响应类型指定不同Content-Type
	        //res.writeHead(200, {
            //    'Content-Type': fileMime
            //});
		}catch(e) {
            console.log(e);
            content = `<h1>404-什么也没找到</h1>`;
            response.writeHead(404, {
                'Content-Type': 'text/html;charset=utf-8'
            });
         }
         response.write(content);
    } else {
        response.setHeader('Content-Type', 'text/html;charset=utf-8');
        response.write(`
                <h1>响应的内容</h1>
        `);
    }   
    response.end();
});

server.listen(8081, () => {
    console.log('服务启动成功,您可以通过:http://localhost:8081')
});
  • 访问:
    • http://localhost:8081/test/index.html
    • http://localhost:8081/test/images/logo.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值