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. Linux 判断进程是否运行

    问题 linux平台 多人开发服务器,有时自己运行一个进程在服务器上,但未知原因导致停止运行了,需要添加一个定时任务,用于监控指定进程是否运行 方法 一个通用的方法,以便使用在不同项目中. 思路:定时 ...

  2. JavaBean是什么,POJO是什么

    参考:https://stackoverflow.com/questions/3295496/what-is-a-javabean-exactly https://stackoverflow.com/ ...

  3. 【C++】读取参数的类

    在C++程序中,如果我们把程序中的参数都保存在txt文本中,运行时再去读取.这样的好处是,当我们需要调参的时候,不需要每次都重新编译程序,大大提升了效率. 今日分享一份实现以上功能的代码,代码来源:h ...

  4. 关于想通过ros的dstnat实现公网IP nat 公网IP的情况

    转发群里大神的“苏州-海豚在跳舞”的图 理论上客户机收到2.2.2.2过来的包应该直接丢弃.因为它并没有给2.2.2.2发过包.这里不知道如果在2.2.2.2上做 src-nat伪装成1.1.1.1回 ...

  5. 并发之volatile底层原理

    15.深入分析Volatile的实现原理 14.java多线程编程底层原理剖析以及volatile原理 13.Java中Volatile底层原理与应用 12.Java多线程-java.util.con ...

  6. linux vue项目+npm run build + nginx

    系统 环境 vue   nginx 步骤 1.打包vue项目 2.配置nginx 打包vue项目 1.项目配置   我们使用服务器的8000端口 2.打包 # npm run build 打包成功会创 ...

  7. JavaWeb——jsp-config

    <jsp-config> 包括 <taglib> 和 <jsp-property-group> 两个子元素.其中<taglib> 元素在JSP 1.2 ...

  8. SpringMVC 启动流程

    首先看一下Web应用部署初始化过程 (Web Application Deployement),官方文档说明: Web Application Deployment When a web applic ...

  9. Linux操作系统监控分析

    性能分析点:1. 负载机2.网络传输3.硬件4.应用程序线程池5.数据库连接池6.代码业务逻辑7.数据库sql执行时间8.jvm(GC) 操作系统硬件:cpu:计算.逻辑处理:CPU的颗粒数越多,CP ...

  10. 阿里云服务器 CentOS 安装Mysql 5.6

    下载:https://dev.mysql.com/downloads/file/?id=471181   第一步: 安装mysql5姿势是要先安装带有可用的mysql5系列社区版资源的rpm包 [ro ...