express是一个基于node.js平台的,快速,开放,极简的web开发框架。

一、安装 express

npm install express --save

  

二、简单使用 express

//引入express
const express = require('express');
//创建一个应用
let app = express(); //匹配GET请求路径设置回调函数
app.get('/hello', function (req, res) {
res.end('hello');
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

通过访问 localhost:8888/hello 我们就可以看到内容输出了。

当然 express 还支持其他的一些请求方法,比如 app.post(),app.put(),app.delete(),app.head() 等。

//引入express
const express = require('express');
//创建一个应用
let app = express(); //匹配POST请求
app.post('/hello', function (req, res) {
res.end('post hello');
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

如果我们想要匹配所有的请求路径,可以使用通配符 * 号。

//引入express
const express = require('express');
//创建一个应用
let app = express(); app.get('/hello', function (req, res) {
res.end('hello');
}); //*号匹配所有路径
app.get('*', function (req, res) {
res.end('not found');
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

express 还提供了 all() 方法,可以匹配所有请求方法。

//引入express
const express = require('express');
//创建一个应用
let app = express(); //匹配所有请求方法
app.all('/hello', function (req, res) {
res.end('all hello');
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

  

三、express 中间件的概念

express中间件就是处理http请求的函数,用来完成一些特定的操作,比如登陆检查,权限控制等等。

1、一个中间件处理完请求和响应,可以把数据传递给下一个中间件。

2、在回调函数中使用 next(),就可以让请求继续向下传递。

3、通过不同路径,分别执行不同的中间件。

我们可以使用 use() ,在路由数组中添加一个中间件。注意我们设置的路由路径最终会存放在一个数组里,由上到下的把路径加入这个数组中。

//引入express
const express = require('express');
//创建一个应用
let app = express(); //如果没有设置路径,则会匹配全部
app.use(function (req, res, next) {
console.log('匹配全部路径');
//注意这里如果不调用next(),则请求并不会向下传递。
next();
}); app.use('/hello', function (req, res, next) {
console.log('use hello');
next();
}); app.get('/hello', function (req, res, next) {
console.log('get hello');
next();
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

next() 函数可以传入一个参数,表示错误信息,默认将执行错误中间件。

//引入express
const express = require('express');
//创建一个应用
let app = express(); app.get('/hello', function (req, res, next) {
console.log('get hello');
next('error!!!');
}); //注意错误处理中间件的参数是4个
app.use(function (err, req, res, next) {
console.log(err);
res.end(err);
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

  

四、express中的request对象

在express中对原生的req请求对象进行了扩展,添加了一些属性和方法。

//引入express
const express = require('express');
//创建一个应用
let app = express(); app.get('/hello', function (req, res, next) {
//主机名
res.write('req.hostname : ' + req.hostname + '\r\n');
//请求URL的路径
res.write('req.path : ' + req.path + '\r\n');
//查询字符串对象
res.write('req.query : ' + JSON.stringify(req.query) + '\r\n');
//请求的远程IP地址
res.write('req.ip : ' + req.ip + '\r\n');
//请求方法
res.write('req.method : ' + req.method + '\r\n');
res.end();
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

通过 req.params 获取路径里的参数

//引入express
const express = require('express');
//创建一个应用
let app = express(); app.get('/list/:key/:page/:size', function (req, res, next) {
//注意,设置了多少参数,地址就需要传入多少参数
res.end(JSON.stringify(req.params));
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

  

五、express中的response对象

express中也对原生的res对象进行了扩展,添加了一些属性和方法。

const path = require('path');
//引入express
const express = require('express');
//创建一个应用
let app = express(); app.get('/send/str', function (req, res, next) {
//send方法会自动判断数据类型,并进行相应的head信息设置
//如果参数是字符串,则Content-Type为 text/html
res.send('hello, world');
}); app.get('/send/arr', function (req, res, next) {
//如果参数是一个数组,则返回json
res.send([1, 2, 3]);
}); app.get('/send/obj', function (req, res, next) {
//如果参数是一个对象,则返回json
res.send({name: 'xiaoxu', age: 24});
}); app.get('/send/number', function (req, res, next) {
//如果是一个数字,则返回相应状态码短语
res.send(404);
}); app.get('/download', function (req, res, next) {
//提示下载文件
res.download('./1.txt');
}); app.get('/json', function (req, res, next) {
//响应json对象
res.json({name: 'xiaoxu'});
}); app.get('/jsonp', function (req, res, next) {
//客户端请求时,需要带上callback=test
res.jsonp('hello');
}); app.get('/redirect', function (req, res, next) {
//重定向到一个地址
res.redirect('http://www.baidu.com');
}); app.get('/sendfile', function (req, res, next) {
//发送一个文件
res.sendFile(path.resolve('./1.txt'));
}); app.get('/sendstatus', function (req, res, next) {
//发送一个状态码
res.sendStatus(302);
}); //监听端口
app.listen(8888, function () {
console.log('port : 8888');
});

  

六、ejs模板的使用

支持express的模板有很多种,这里我们使用ejs作为模板引擎。

安装ejs:

npm install ejs

使用ejs模板

const path = require('path');
const express = require('express');
//创建一个应用
let app = express();
//设置模板引擎
app.set('view engine', 'ejs');
//设置模板目录
app.set('views', path.join(__dirname, 'views'));
//监听
app.listen(8888);

如果我们希望,ejs能够渲染html页面,可以使用如下

const path = require('path');
const express = require('express');
let app = express(); //设置视图引擎为html引擎
app.set('view engine', 'html');
//设置视图的路径
app.set('views', path.join(__dirname, 'views'));
//配置html引擎
app.engine('html', require('ejs').__express); app.listen(8888);

渲染视图,输出内容。

const path = require('path');
const express = require('express');
let app = express(); app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').__express); app.get('/hello', function (req, res, next) {
//参数一表示模板的名称,会在当前项目目录下的views目录查找
//参数二表示传入模板中的数据
res.render('hello', {
name: 'xiaoxu',
age: 24
});
}); app.listen(8888);

hello.html的代码:

<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<%= name %>
<%= age %>
</body>
</html>

  

七、静态文件服务器

有些时候我们需要在页面上加载css,js,img等静态资源,指定存放静态资源的目录,浏览器发出非html文件请求时,服务器会到这个目录下找对应的资源。

const path = require('path');
const express = require('express');
let app = express(); app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').__express); //注意express.static这个中间件是express内置的
app.use(express.static(path.join(__dirname, 'public'))); app.get('/hello', function (req, res, next) {
//参数一表示模板的名称,会在当前项目目录下的views目录查找
//参数二表示传入模板中的数据
res.render('hello', {
name: 'xiaoxu',
age: 24
});
}); app.listen(8888);

  

八、使用body-parser中间件解析post过来的数据

安装body-parser

npm install body-parser

使用body-parser

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
let app = express(); app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').__express); //解析 application/json
app.use(bodyParser.json());
//解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended:false})); app.post('/form', function (req, res) {
console.log(req.body);
}); app.listen(8888);

  

node.js中express框架的基本使用的更多相关文章

  1. node.js使用express框架进行文件上传

    关于node.js使用express框架进行文件上传,主要来自于最近对Settings-Sync插件做的研究.目前的研究算是取得的比较好的进展.Settings-Sync中通过快捷键上传文件,其实主要 ...

  2. node.js之express框架

    之前学习过node.js接触过express框架,最近为了编写一个mock server正好用到了express.下面正好就跟大家介绍一下关于express.今天的内容主要围绕这么几个方面? expr ...

  3. node.js中的框架

    node.js中的框架 载自: http://nodeframework.com/ MVC frameworks Sinatra-like These frameworks offer rich co ...

  4. node.js中express模块创建服务器和http模块客户端发请求

    首先下载express模块,命令行输入 npm install express 1.node.js中express模块创建服务端 在js代码同文件位置新建一个文件夹(www_root),里面存放网页文 ...

  5. Node.js基于Express框架搭建一个简单的注册登录Web功能

    这个小应用使用到了node.js  bootstrap  express  以及数据库的操作 :使用mongoose对象模型来操作 mongodb 如果没了解过的可以先去基本了解一下相关概念~ 首先注 ...

  6. node.js之express框架入门篇

    一.express框架简介 express框架是后台的Node框架,在后台的受欢迎的程度,和jQuery一样 英语官网:http://expressjs.com/ 中文官网:http://www.ex ...

  7. 【node.js】Express 框架

    Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具. 使用 Express 可以快速地搭建一个完整功能的网 ...

  8. Node.js:Express 框架

    Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具.使用 Express 可以快速地搭建一个完整功能的网站 ...

  9. Node.js、Express框架获取客户端IP地址

    Node.js //传入请求HttpRequest function getClientIp(req) { return req.headers['x-forwarded-for'] || req.c ...

随机推荐

  1. Python小练习(一)

    1:有一个列表,其中包括10个元素,例如这个列表是[1,2,3,4,5,6,7,8,9,0],要求将列表中的每个元素一次向前移动一个位置,第一个元素到列表的最后,然后输出这个列表.最终样式是[2,3, ...

  2. redis 的备份策略,最好使用:RDB-AOF 混合持久化

    相关资料: Redis 4.0 新功能简介:RDB-AOF 混合持久化:http://blog.huangz.me/2017/redis-rdb-aof-mixed-persistence.html ...

  3. PHP使用文件锁解决高并发问题示例

    新建一个.txt文件,文件中什么都不用写. [一].阻塞(等待)模式:(只要有其他进程已经加锁文件,当前进程会一直等其他进程解锁文件) <?php //连接数据库 $con=mysqli_con ...

  4. [转]Python依赖打包发布详细

    Python依赖打包发布详细   http://www.cnblogs.com/mywolrd/p/4756005.html 将Python脚本打包成可执行文件   Python是一个脚本语言,被解释 ...

  5. 文件处理,三元操作符,seek()函数,迭代函数和列表解析,reduce函数

    1.文件读取方类型 r,r+,w,x,a, r,读文件 w,写文件,文件内容全部删除,并将新内容从第一行开始赋值 x,写文件,只有文件不存在,可写,文件存在,报错 a,在文件莫问追加信息 r+,w+, ...

  6. <realsense D400>同步采集深度图和彩色图

    利用深度相机采集深度图和彩色图会面临一个问题,如何实现同步采集数据? 以下是我搜集到的两点方法: 1)高翔博士提到他的orbslam2教程有这么一步工作,具体目录为 example/RGBD/. (等 ...

  7. pyhton3.5将汉字转成二进制的方法

    直接上代码:name = "你好,中国人"byteName = bytes(name.encode("utf-8"))print(byteName)for b ...

  8. nginx的启动与停止

    参考 :http://www.cnblogs.com/codingcloud/p/5095066.html 启动: /usr/local/nginx/sbin/nginx -c /usr/local/ ...

  9. python之路——11

    王二学习python的笔记以及记录,如有雷同,那也没事,欢迎交流,wx:wyb199594 学习内容 一.装饰器 1.时间模块 time.time time.sleep 2.装饰器 原则---开放封闭 ...

  10. 保存数据到Excel中

    调用的方法传值 Export(dt, "Cal_Report_" + DateTime.Now.ToString("yyyyMMddhhmmss") + &qu ...