1. 项目初始化
ps:我是用 webstrom 打开终端控制台操作的
1.1创建项目目录
随便在电脑一个位置,用终端创建文件夹
// 目录名自定义,我的是admin-wyl-node
mkdir admin-wyl-node

1.2 初始化项目
// 先进入 创建的文件夹路径
cd admin-wyl-node
// 初始化项目
npm init -y

1.3安装依赖
cnpm i -S express

1.4. 创建 app.js 文件
// 1. 引入express包
const express = require('express')
// 创建一个express的应用
const app = express()
// 创建基于路由的监听
app.get('/',function (req,res) {
// 监听 根路径/ 的get请求,通过 根路径/ 返回给浏览器
// 通过 get 请求的时候会返回个客户端
res.send('hello node')
})
// 将整个项目运行起来,使expres 监听 5000 端口号发起的 http请求
const server = app.listen(5000, function () {
// 监听 路径和端口号
const { address, port } = server.address()
console.log('HTTP启动成功:http://%s:%s', address, port);
})
1.5. 启动项目
1.5.1 修改package.json

1.5.2 启动项目
node app.js

1.5.3 在浏览器中输入 localhost:5000 出现如下界面,即成功。

2. expres基础概念
2.1 中间件
在 app.js 文件 编写。大多数中间件在响应结束前被调用。
/**
* 创建 回调函数
* 写一个中间函数
* 调用中间件注意事项:
* 1. next() 必须调用,否则不会向下执行,也就是说 执行完上上面的代码后,
* next() 下面的代码不会再执行了,会一直等待
* 2. 中间件一定要在发起请求之前调用(在app.get()方法前调用),否则请求已经执行完毕,也不会去调用中间件
*/
function myLogger( req, res, next){
console.log('myLogger');
next()
}
// 通过 app.use() 使用中间件,和 vue 加载插件非常相似
app.use(myLogger)


2.2 路由
路由 是 应用如何请求的一种规则
规则主要分两部分:
- 请求方法: get ,post ......
- 请求的路径:/ , /user, /*user$/......
请求的方法和路径要匹配,否则会出错
响应 / 路径的 get 请求:
// 之前创建app.js的时候就已经创建了下面这个路由
app.get('/', function(req, res) {
res.send('hello node')
})
响应 / 路径的 post 请求:
app.post('/', function(req, res) {
res.send('hello node')
})
// 出错
app.post('/user',function (req,res) {
res.json('user...')
})

2.3 异常处理
其实也是一个中间件
使用时需要注意两点:
第一,4个参数一个不能少,否则会视为普通的中间件
第二,中间件需要在请求之后引用
// 后置的处理请求通常用来做异常处理,而前置的都是些如日志、跨域这类操作
// 先删除mylogger函数,再创建中间件,并修改get请求方法
app.get('/',function (req,res) {
throw new Error('error...')
})
function errorHandler(err, req, res, next){
// 打印 错误信息
console.log(err);
// 设置 返回错误码500
res.status(500).json({
error: -1,
msg: err.toString()
})
}
app.use(errorHandler)


2.4 项目框架优化
2.4.1 安装boom依赖
可以快速生成异常信息
cnpm i -S boom

将之前的路由删除掉,最后app.js文件如下:
// 1. 引入express包
const express = require('express')
// 创建一个express的应用
const app = express()
// 将整个项目运行起来,使expres 监听 5000 端口号发起的 http请求
const server = app.listen(5000, function () {
// 监听 路径和端口号
const { address, port } = server.address()
console.log('HTTP启动成功:http://%s:%s', address, port);
})
2.4.2 项目根目录下创建router文件夹
这个文件夹用来处理全局异常,即将整个路由变成中间件。
router文件夹下创建index.js文件
// app.js种添加代码,将全局路由托管到router下,利于代码维护和简洁
const router = require('./router') // 文件路径是前面创建的router文件夹
app.use('/', router)

router/index.js
const express = require('express')
const boom = require('boom')
const userRouter = require('./user')
const {
CODE_ERROR
} = require('../utils/constant')
// 注册路由
const router = express.Router()
router.get('/', function (req, res) {
res.send('欢迎学习小琳读书管理后台')
})
// 通过 userRouter 来处理 /user 路由,对路由处理进行解耦
//路由嵌套 /user/info
router.use('/user', userRouter)
/**
* 集中处理404请求的中间件
* 注意:该中间件必须放在正常处理流程之后
* 否则,会拦截正常请求
*/
router.use((req, res, next) => {
next(boom.notFound('接口不存在'))
})
/**
* 自定义路由异常处理中间件
* 注意两点:
* 第一,方法的参数不能减少
* 第二,方法的必须放在路由最后
*/
// 可将下面这段代码注释掉查看运行结果
router.use((err, req, res, next) => {
console.log(err);
const msg = (err && err.message) || '系统错误'
const statusCode = (err.output && err.output.statusCode) || 500
const errorMsg = (err.output && err.output.payload && err.output.payload.error) || err.message
res.status(statusCode).json({
code: CODE_ERROR,
msg,
error: statusCode,
errorMsg
})
})
module.exports = router
router/user.js
const express = require('express')
const router = express.Router()
router.get('/info', function(req, res, next) {
res.json('user info...')
})
module.exports = router
utils/constant:
module.exports = {
CODE_ERROR: -1
}
输入网址http://localhost:5000/aaa查看结果。注意运行命令node app.js查看结果。

网友评论