稍作修改,改成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代码:
![测试图片](./img/test.jpg)
如果本地直接双击打开,效果是这样滴:
现在我们要做的就是如何通过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
启动项目: