node.js入门学习(二)MIME模块,request和response对象,demo之不同url请求不同html页面,页面包含图片、样式css等静态资源
目录:
一、构建http服务程序-根据不同请求做出不同响应
二、根据用户不同请求,读取不同HTML文件响应
三、响应的HTML文件中包含图片的处理方式
四、根据后缀查询MIME类型
五、案例:不同url请求不同html页面,页面包含图片、样式css等静态资源
六、request对象
七、response对象常用成员(API)
一、构建http服务程序-根据不同请求做出不同响应 <--返回目录
// 加载http模块
var http = require("http"); // 创建一个http服务对象
http.createServer(function(req, res) {
if(req.url === '/') {
res.end("hello index");
} else if(req.url === '/list') {
res.end("hello list");
} else {
res.end("404,not found!");
}
}).listen('8080', function() {
console.log('服务器已经启动。');
});
二、根据用户不同请求,读取不同HTML文件响应 <--返回目录
第一步:在D:/hello.js中写代码:
// 加载http模块
var http = require("http");
var fs = require("fs");
var path = require("path"); // 创建一个http服务对象
http.createServer(function(req, res) {
if(req.url === '/') {
fs.readFile(path.join(__dirname, 'pages/index.html'), function(err, data) {
if(err) throw err;
res.end(data);
});
} else if(req.url === '/list') {
fs.readFile(path.join(__dirname, 'pages/list.html'), function(err, data) {
if(err) throw err;
res.end(data);
});
} else {
res.end("404,not found!");
}
}).listen('8080',function() {
console.log('服务器已经启动。');
});
第二步:在d盘下创建pages文件夹,在pages文件夹中添加index.html文件和list.html文件
index.html(list.html把index替换成list)
<!DOCTYPE html>
<html>
<head>
<title>index页面</title>
<meta charset="utf-8">
</head>
<body>
<h2>index页面</h2>
</body>
</html>
第三步:浏览器访问:http://localhost:8080/list
三、响应的HTML文件中包含图片的处理方式 <--返回目录
第一步:在D:/hello.js中写代码:
// 加载http模块
var http = require("http");
var fs = require("fs");
var path = require("path"); // 创建一个http服务对象
http.createServer(function(req,res) {
if(req.url === '/') {
fs.readFile(path.join(__dirname, 'pages/index.html'), function(err, data) {
if(err) throw err;
res.end(data);
});
} else if(req.url === '/list') {
fs.readFile(path.join(__dirname, 'pages/list.html'), function(err, data) {
if(err) throw err;
res.end(data);
});
} else if(req.url.includes('.jpg')){
fs.readFile(path.join(__dirname, 'images', req.url), function(err, data) {
if(err) throw err;
res.end(data);
});
} else {
res.end("404,not found!");
}
}).listen('8080',function() {
console.log('服务器已经启动。');
});
第二步:在d盘下创建pages文件夹,在pages文件夹中添加index.html文件和list.html文件
index.html文件
<!DOCTYPE html>
<html>
<head>
<title>index页面</title>
<meta charset="utf-8">
</head>
<body>
<h2>index页面</h2>
<img src="/1.jpg">
</body>
</html>
第三步:在d盘下创建images文件夹,在images文件夹中添加1.jpg文件
第四步:浏览器访问:http://localhost:8080
四、根据后缀查询MIME类型 <--返回目录
请求的静态资源可能是图片,可能是css等等,图片后缀可能是jpg,可能是png等等。为了写出通用的程序,可以使用第三方模块mime。
使用第三方模块mime:
// 根据请求后缀,来决定返回数据的MIME类型
var mime = require("mime");
res.setHeader('Content-Type', mime.getType(req.url));
五、案例:不同url请求不同html页面,页面包含图片、样式css等静态资源 <--返回目录
项目结构:

在项目根目录node-hello下,执行npm install mime命令,下载安装mime模块;安装完后会在node-hello目录下创建node_modules目录。
app.js
// 加载http模块
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime"); // 创建一个http服务对象
http.createServer(function(req,res) {
if(req.url === '/') {
fs.readFile(path.join(__dirname, 'pages/index.html'), function(err, data) {
if(err) throw err;
res.end(data);
});
} else if(req.url === '/list') {
fs.readFile(path.join(__dirname, 'pages/list.html'), function(err, data) {
if(err) throw err;
res.end(data);
});
} else if(req.url.includes('static')){
fs.readFile(path.join(__dirname, req.url), function(err, data) {
if(err) {
res.end("文件不存在!");
return;
}
res.setHeader('Content-Type', mime.getType(req.url));
res.end(data);
});
} else {
res.end("404,not found!");
}
}).listen('8080',function() {
console.log('服务器已经启动。');
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>index页面</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/static/css/common.css">
</head>
<body>
<h2>index页面</h2>
<img src="/static/images/1.jpg">
<img src="/static/images/2.png">
</body>
</html>
请求静态资源时,响应信息:

如果不使用mime,并且将res.setHeader('Content-Type', mime.getType(req.url));注释掉,其实静态资源也能正常处理。
六、request对象 <--返回目录
1)request对象类型http.IncomingMessage,继承自stream.Readable;
2)request对象常用成员
- request.headers 获取所有的请求报文头,返回一个对象{'host':'localhost:8080', 'Connection':'keep-alive', ...}
- request.rawHeaders 获取所有的请求报文头,返回一个数组 ['host','localhost:8080','Connection','keep-alive', ...]
- request.httpVersion 获取客户端使用的http版本
- request.method 请求是get还是post
- request.url
七、response对象常用成员(API) <--返回目录
1) response.write('数据',['数据编码'],[fn]);
2) response.end();//结束响应
3) response.end([data], [encoding], [callback]);
- 该方法中如果指定了data,则相当于调用response.write(data,encoding)之后再调用response.end(callback)
4) response.setHeader('','');//在响应内容前设置,设置响应报文头
5) 设置http响应状态码和对应的消息
response.statusCode=404
response.statusMessage='Not Found';
6) response.writeHead() 直接向客户端写入http响应报文头
response.writeHead(404,'Not Found', {'Content-Type':'text/html;charset=utf-8'})
node.js入门学习(二)MIME模块,request和response对象,demo之不同url请求不同html页面,页面包含图片、样式css等静态资源的更多相关文章
- Node.js入门学习笔记(一)
先来个最常见的"Hello World!". 打开你最喜欢的编辑器(我用的是Sublime Text),创建一个helloWorld.js的文件.我们要做的就是向stdout输出& ...
- node.js入门学习笔记整理
(1)node Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node与javaScript的区别在于,javaScript的顶层对象是window,而no ...
- node.js入门学习(一)环境安装,REPL,fs模块,path模块,http模块
一.node.js介绍 1.1.node.js是什么 官网首页总结:Node.js® 是一个基于 Chrome V8 引擎 的 JavaScript 运行时. 1)node.js是一个开发平台,就像j ...
- node.js入门学习(四)--Demo图书的增删改查
需求:图书的增删改查,图书数据保存在data.json文件中. 1.Demo结构: 2.首先下载安装node.js,配置环境变量:参考博客 3.项目初始化 1)创建项目根目录node-hello,进入 ...
- 手把手教你学node.js之学习使用外部模块
学习使用外部模块 目标 建立一个 lesson2 项目,在其中编写代码. 当在浏览器中访问 http://localhost:3000/?q=alsotang 时,输出 alsotang 的 md5 ...
- node.js入门学习(五)--Demo模块化改造
1.node.js中模块的分类 1)node.js内置模块(核心,原生) 所有内置模块在安装node.js时就已经编译成二进制文件,可以直接加载运行(速度较快),部分内置模块,在node.exe这个进 ...
- node.js入门学习(三)--npm
一.npm介绍 1)npm:node package manager是node.js默认的以js编写的软件包管理系统 官网:www.npmjs.com 文档:docs.npmjs.com 2)提到np ...
- Node.js基础学习二之POST请求
本篇介绍下 Node.js post 请求 需求: 用户登录,前端界面输入用户名和密码,点击登录请求后台验证,根据后台反馈的信息做出响应 前端: (1)使用form表单 (2)使用ajax异步请求 服 ...
- Node.js入门学习笔记(三)
基于事件驱动的回调 这个问题不好回答,不过这是Node.js原生的工作方式.它是事件驱动的,这也是它为什么这么快的原因.你可以花一点时间阅读一下Felix Geisendörfer的大作 Unders ...
随机推荐
- SQL修改数据表字段长度
alter table m_Assysn_t nocheck CONSTRAINT allAlter Table m_Assysn_t ALTER column ppid VARCHAR(150)al ...
- c++ xml 解析“后直接跟值问题
c++ xml库相关 要解析内容: <ITEM name="SLSJ"head="SLSJ"/> 代码: GetNodeAttri(subnodes ...
- HDU 1133 Buy the Ticket (数学、大数阶乘)
Buy the Ticket Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)To ...
- 洛谷 P2015 二叉苹果树 题解
题面 裸的树上背包: 设f[u][i]表示在以u为子树的树种选择i条边的最大值,则:f[u][i]=max(f[u][i],f[u][i-j-1]+f[v][k]+u到v的边权); #include ...
- Luogu P2501 [HAOI2006]数字序列
题目 首先把\(a\)改成严格单调上升等于把\(a_i-i\)改成单调不降. 那么第一问可以直接做LIS,答案就是\(n-\)LIS的长度. 同时我们记录一下序列中每个位置结尾的LIS长度. 第二问我 ...
- rebtree学习
http://www.cnblogs.com/skywang12345/p/3245399.html http://www.cnblogs.com/skywang12345/p/3624177.htm ...
- vue render 渲染函数
vue render 渲染函数 经常看到使用render渲染函数的示例,而且在一些特殊情况下,确实更好使用,可以更加有效地细分组件,因而借助vue-element-admin来学习一波 render函 ...
- C#实现Web链接启动应用程序
C#实现Web链接启动应用程序 最近需要配合Web端实现用户点击链接来启动应用程序并且需要能够传参数给应用程序. 那么就可以使用注册表来实现这个功能 编写注册表可以在软件安装程序中加入,也可以在软件启 ...
- Android中res下anim和animator文件夹区别与总结
1.anim文件夹 anim文件夹下存放tween animation(补间动画)和frame animation(逐帧动画) 逐帧动画: ①在animation-list中使用item定义动画的全部 ...
- iPad和iPhone上的应用程序图标
iPad和iPhone上的应用程序图标 问:如何在iPad和iPhone使用我的应用程序包中的图标文件? 答:下面是处理文件的图标为iPhone专用的应用程序,iPad的专用应用程序,以及通用的应用程 ...