node.js中express框架的基本使用
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框架的基本使用的更多相关文章
- node.js使用express框架进行文件上传
关于node.js使用express框架进行文件上传,主要来自于最近对Settings-Sync插件做的研究.目前的研究算是取得的比较好的进展.Settings-Sync中通过快捷键上传文件,其实主要 ...
- node.js之express框架
之前学习过node.js接触过express框架,最近为了编写一个mock server正好用到了express.下面正好就跟大家介绍一下关于express.今天的内容主要围绕这么几个方面? expr ...
- node.js中的框架
node.js中的框架 载自: http://nodeframework.com/ MVC frameworks Sinatra-like These frameworks offer rich co ...
- node.js中express模块创建服务器和http模块客户端发请求
首先下载express模块,命令行输入 npm install express 1.node.js中express模块创建服务端 在js代码同文件位置新建一个文件夹(www_root),里面存放网页文 ...
- Node.js基于Express框架搭建一个简单的注册登录Web功能
这个小应用使用到了node.js bootstrap express 以及数据库的操作 :使用mongoose对象模型来操作 mongodb 如果没了解过的可以先去基本了解一下相关概念~ 首先注 ...
- node.js之express框架入门篇
一.express框架简介 express框架是后台的Node框架,在后台的受欢迎的程度,和jQuery一样 英语官网:http://expressjs.com/ 中文官网:http://www.ex ...
- 【node.js】Express 框架
Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具. 使用 Express 可以快速地搭建一个完整功能的网 ...
- Node.js:Express 框架
Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具.使用 Express 可以快速地搭建一个完整功能的网站 ...
- Node.js、Express框架获取客户端IP地址
Node.js //传入请求HttpRequest function getClientIp(req) { return req.headers['x-forwarded-for'] || req.c ...
随机推荐
- extjs_10_自己定义combotree组件
1.项目截图 2.treedata.json { text : "root", expanded : true, expandable : true, children : [{ ...
- Java自定义类加载器与双亲委派模型
其实,双亲委派模型并不复杂.自定义类加载器也不难!随便从网上搜一下就能搜出一大把结果,然后copy一下就能用.但是,如果每次想自定义类加载器就必须搜一遍别人的文章,然后复制,这样显然不行.可是自定义类 ...
- Java种的String
String中的常用方法 subString()的使用,charAt的使用方法: indexof等的用法 String和byte的转换,对于程序过程的传输很重要, ==和equals的比较 1equa ...
- select函数与I/O多路转接
select函数与I/O多路转接 相作大家都写过读写IO操作的代码,例如从socket中读取数据可以使用如下的代码: while( (n = read(socketfd, buf, BUFSIZE) ...
- vue-cli脚手架build目录中的build.js配置文件
该随笔收藏自: vue-cli脚手架build目录中的build.js配置文件 这个配置文件是命令npm run build 的入口配置文件,主要用于生产环境 由于这是一个系统的配置文件,将涉及很多的 ...
- python中定时任务
今天看网络框架时,突然想看一下定时器,于是往上搜索了一下python中timer task的实现,但是由于python本身对线程的支持不是太好,因为全局排它锁的存在,使得多线程在访问资源时效率比较低. ...
- python中的第三方日志模块logging
基本上每个系统都有自己的日志系统,可以使自己写的,也可以是第三方的.下面来简单介绍一下python中第三方的日志模块,入手还是比较简单的,但是也很容易给自己埋雷. 下面是我参考的资料链接 入手demo ...
- 成为JavaGC专家—深入浅出Java垃圾回收机制
对于Java开发人员来说,了解垃圾回收机制(GC)有哪些好处呢? 首先可以满足作为一名软件工程师的求知欲, 其次,深入了解GC如何工作可以帮你写出更好的Java应用. 这仅仅代表我个人的意见,但我坚信 ...
- Java -- XStreamAlias 处理节点中的属性和值
XStreamAlias 可以把objec和xml相互转换,但是有时候节点带有属性和值就需要特殊处理下: <?xml version="1.0" encoding=" ...
- spring boot 错误处理总结
在boot 中, 对404 和 异常 有了额外的处理. 当然,我们可以定制, 如何做呢? 1 写一个继承 ErrorController 的Controller 注意, 这里一定要继承 ErrorC ...