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 ...
随机推荐
- 简单的shell脚本练习(一)
1:求1000一内的偶数和 方法一: #!/bin/bash #用累加实现1000以内的偶数和 sum= ;i<=;i=i+)) do sum=$(($sum+$i)); done echo $ ...
- [转]使用python爬取东方财富网机构调研数据
最近有一个需求,需要爬取东方财富网的机构调研数据.数据所在的网页地址为: 机构调研 网页如下所示: 可见数据共有8464页,此处不能直接使用scrapy爬虫进行爬取,因为点击下一页时,浏览器只是发起了 ...
- c#读sql server数据添加到MySQL数据库
using System;using System.Collections.Generic;using System.Text;using Console = System.Console;using ...
- GradleUserGuide中文版 19)Plugins 20)插件规范 21)Java插件
https://blog.csdn.net/roymuste/article/details/51321881
- plot
scatter import pandas as pd df_train=pd.read_excel(r"C:\Users\Liugengxin\Desktop\回归.xlsx") ...
- System类学习笔记
最近在学习源码的过程中发现:很多深层次的代码都用到了一个类System类,所以决定对System类一探究竟 本文先对System类进行了剖析,然后对System类做了总结 一.首先对该类的中的所有字段 ...
- iframe-父子-兄弟页面相互传值(jq和js两种方法)
参考文章: http://blog.csdn.net/u013299635/article/details/78773207 http://www.cnblogs.com/xyicheng/archi ...
- web socket client
<!DOCTYPE HTML> <html> <head> <title>My WebSocket</title> </head> ...
- python中的第三方日志模块logging
基本上每个系统都有自己的日志系统,可以使自己写的,也可以是第三方的.下面来简单介绍一下python中第三方的日志模块,入手还是比较简单的,但是也很容易给自己埋雷. 下面是我参考的资料链接 入手demo ...
- java数据类型关系及关系
java中有常见的基本数据类型和引用数据类型,基本数据类型为四类八种如下 整数型(byte,short,int,long) 浮点型(float,double) 字符型(char) 布尔型(boolea ...