nodejs项目实战教程08——创建静态Web服务器

稍作修改,改成es语法,端口修改成不重复的,甚至响应头,并且读取一下请求路径做下过滤:

var http = require(‘http’);

http.createServer((req, res)=>{

// 1.获取地址

let pathname = req.url

// 过滤网站tab图标请求

if(pathname !== ‘/favicon.ico’){

console.log(pathname)

// 设置响应头

res.writeHead(200, {‘Content-Type’: ‘text/html;charset=“utf-8”’});

res.end(‘Hello World’);

}

}).listen(3000);

console.log(‘Server running at http://127.0.0.1:3000/’);

在这里插入图片描述

在这里插入图片描述

1.2 读取服务器上的资源文件

创建demo10项目,static文件夹下是网页的静态资源,其中,index.html文件引用到了css、img下的文件(详细的样式和图片资源并不重要,可以随便写,这里只是为了说明多文件的读取问题)。

在这里插入图片描述

index.html代码:

Document
你好
测试图片

如果本地直接双击打开,效果是这样滴:

在这里插入图片描述

现在我们要做的就是如何通过nodejs读取html及其引用的文件,并显示在服务器中。具体代码如下,app.js:

// 创建一个web服务器

// 1.可以访问web服务器上的网站

// 2.可以下载web服务器上的文件

const http = require(‘http’);

const fs = require(‘fs’)

const common = require(‘./module/common.js’)

const path = require(‘path’)

// common.gtFileMine(‘.css’)

http.createServer(function (req, res) {

// 1.获取地址

let pathname = req.url

// 解析地址,除去地址?后的字符

pathname = (pathname.split(‘?’))[0]

// 默认加载页面

pathname = pathname === ‘/’?‘/index.html’:pathname

// 获取文件后缀

let extname = path.extname(pathname)

// 2.通过fs模块读取文件

if(pathname !== ‘/favicon.ico’){

console.log(pathname)

// console.log(req)

fs.readFile(‘./static’ + pathname,(err,data)=>{

if(err){

res.writeHead(404, {‘Content-Type’: ‘text/html;charset=“utf-8”’});

res.end(‘这个页面不存在’);

}

// 根据路径后缀返回content-type

// let mime = common.getMime(extname);

let mime = common.gtFileMine(extname);

res.writeHead(200, {‘Content-Type’: ‘’+ mime +‘;charset=“utf-8”’});

// 3.返回路径下文件的内容

res.end(data);

})

}

}).listen(3000);

console.log(‘Server running at http://127.0.0.1:3000/’);

nodemon app.js 启动项目:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值