Node后端Express框架 Node后端Express框架安装及应用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Node后端Express框架 Node后端Express框架安装及应用

李猫er   2021-08-27 我要评论
想了解Node后端Express框架安装及应用的相关内容吗,李猫er在本文为您仔细讲解Node后端Express框架的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Node后端,Express框架安装应用,下面大家一起来学习吧。

Express 框架核心特性:

  • 可以设置中间件来响应 HTTP 请求。
  • 定义了路由表用于执行不同的 HTTP 请求动作。
  • 可以通过向模板传递参数来动态渲染 HTML 页面。

Express安装

express的使用过程有两种方式:

  •  方式一:通过express提供的脚手架,直接创建一个应用的骨架;
  • 方式二:从零搭建自己的express应用结构;

方式一:安装express-generator

npm install -g express-generator

创建项目

express express-app

项目目录如下

├── app.js
├── bin
│   └── www
├── package-lock.json
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.jade
    ├── index.jade
    └── layout.jade

之后 cd 进入到对应的目录下,然后将项目跑起来:

npm install 
node bin/www
node app.js   

方式二: 自己搭建环境

上面通过express提供的脚手架,直接创建一个应用的骨架;现在我们自己从零搭建项目:

初始化一个新的项目:

npm init -y

安装express:

npm install express

新建app.js

在这里插入图片描述

express 初体验

现在搭建自己的第一个express程序:在app.js中加入如下代码

const express = require('express');
// 创建服务器
const app = express();
app.get('/',(req,res) => {
  res.end("Hello World");
});
app.listen(8000,() => {
  console.log("服务器启动成功~");
})

进入项目根目录下,在终端中将服务器跑起来:

node app.js

到浏览器:访问localhost:8000即可

请添加图片描述

请求和响应

请求的路径中如果有一些参数,可以这样表达:

/users/:userId

request对象中要获取可以通过req.params.userId;

返回数据

返回数据,我们可以方便的使用json

res.json(数据)方式;

const express = require('express');
const app = express();
app.get('/users/:userId', (req, res, next) => {
  console.log(req.params.userId);
  res.json({username: "liyingxia", password: "8i8i8i8i" });
});
app.listen(8000, () => {
  console.log("静态服务器启动成功~");
})

Express 中间件

认识中间件

Express是一个路由和中间件的Web框架,它本身的功能非常少:

Express应用程序本质上是一系列中间件函数的调用;

中间是什么?

中间件的本质就是一个回调函数;

这个回调函数接受三个参数:

请求对象(request对象);

响应对象(response对象);

next函数(在express中定义的用于执行下一个中间件的函数);

中间件中可以执行哪些任务?

执行任何代码;

更改请求(request)和响应(response)对象;

结束请求-响应周期(返回数据);

调用栈中的下一个中间件;

如果当前中间件功能没有结束请求-响应周期,则必须调用 next()将控制权传递给下一个中间件功能,否则,请求将被挂起。

使用中间件

express主要提供了两种方式:app/router.useapp/router.methods这两种方式把中间件应用到我们的应用程序中;

methods指的是常用的请求方式,比如:app.getapp.post

// express 中间件的使用
const express = require('express');
const res = require('express/lib/response');
const app = express();
app.use((req,res,next) => {
  console.log("middleware");
  next();
});
app.use((req,res,next) => {
  console.log("middleware");
  res.end("Hello Common Middleware");
})
app.listen(9000,()=>{
  console.log("中间件服务器启动成功~")
})

path匹配中间件:

//path 路径匹配中间件
app.use('/home',(req,res,next) => {
  console.log("home middleware 中间件");
  next();
});
app.use('/home',(req,res,next) => {
  console.log("home middleware02");
  next();
  res.end("middleware");
});
app.use((req,res,next) =>{
   console.log("middleware");
})

path 和 method 匹配中间件

// path 和 method 匹配中间件
app.get('/home',(req,res,next) => {
  console.log("home get middleware");
  next();
})
app.post('/login',(req,res,next) => {
  console.log("login post middleware");
  next();
});
app.use((req,res,next) => {
  console.log("common middleware");
})
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.post('/login',(req,res,next) => {
  console.log(req.body);
  res.end("登陆成功~");
});

日志记录中间件

如果我们希望将请求日志记录下来,那么可以使用express官网开发的第三方库:morgan
morgan安装:

npm install morgan

如何用?直接作为中间件使用即可:

const loggerWriter = fs.createWriteStream('./log/access.log', {
  flags: 'a+'
})
app.use(morgan('combined', {stream: loggerWriter}));

上传文件中间件

图片上传我们可以使用express官方开发的第三方库:multer

multer安装:

npm install multer

上传文件:

const upload = multer({
  dest: "uploads/"
})

app.post('/upload', upload.single('file'), (req, res, next) => {
  console.log(req.file.buffer);
  res.end("文件上传成功~");
})

添加上传文件后缀名:

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/")
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
  }
})
const upload = multer({
  storage
})
app.post('/upload', upload.single('file'), (req, res, next) => {
  console.log(req.file.buffer);
  res.end("文件上传成功~");
})

上传多张图片:

app.use('/upload', upload.array('files'), (req, res, next) => {
  console.log(req.files);
});

请求和响应

客户端传递到服务器参数的方法常见的是5种:

方式一:通过get请求中的URL的params;

方式二:通过get请求中的URL的query;

方式三:通过post请求中的body的json格式;

方式四:通过post请求中的body的x-www-form-urlencoded格式;

方式五:通过post请求中的form-data格式;

请求解析

方式一:params

请求地址: http://locahost:8000/login/asd/ass

获取参数:

app.use('/login/:id/:name', (req, res, next) => {
  console.log(req.params);
  res.json("请求成功~");
})

方式二:query

请求地址:http://localhost:8000/login?username=liyingxia&password=123456
获取参数:

app.use('/login', (req, res, next) => {
  console.log(req.query);
  res.json("请求成功~");
})

方式三:通过post请求中的body的json格式;

在客户端发送post请求时,会将数据放到body中:客户端可以通过json的方式传递,也可以通过form表单的方式传递;

自己编写中间件来解析JSON:

app.use((req, res, next) => {
  if (req.headers['content-type'] === 'application/json') {
    req.on('data', (data) => {
      const userInfo = JSON.parse(data.toString());
      req.body = userInfo;
    })
    req.on('end', () => {
      next();
    })
  } else {
    next();
  }
})
app.post('/login', (req, res, next) => {
  console.log(req.body);
  res.end("登录成功~");
});

适用express内置的中间件或者使用body-parser来完成:

app.use(express.json());
app.post('/login', (req, res, next) => {
  console.log(req.body);
  res.end("登录成功~");
});

方式四:通过post请求中

body的x-www-form-urlencoded格式;

在这里插入图片描述

解析application/x-www-form-urlencoded:

可以使用express自带的 urlencoded函数来作为中间件:

传入的extended用于表示使用哪一种解析方式:

  • true:使用qs第三方模块;
  • false:使用querystring内置模块;
app.use(express.json());
app.use(express.urlencoded({extended: true}));

app.post('/login', (req, res, next) => {
  console.log(req.body);
  res.end("登录成功~");
});

方式五:通过post请求中的form-data格式;

通过any借助multer去解析一些form-data中的普通数据:

在这里插入图片描述

app.use(upload.any());
app.use('/login', (req, res, next) => {
  console.log(req.body);
});

响应方式

end()类似于http中的response.end方法;

res.end("获取成功~")

json()json方法中可以传入很多的类型:

object、array、string、boolean、number、null等,都会被转换成json格式返回

res.json({name:"liyignxia",password:"123456"});

status()设置状态码

res.status(200);

路由的使用

使用express.Router来创建一个路由处理程序:一个Router实例拥有完整的中间件和路由系统;

// 用户相关的处理
const userRouter = express.Router();

userRouter.get('/', (req, res, next) => {
  res.end("用户列表");
});

userRouter.post('/', (req, res, next) => {
  res.end("创建用户");
});

userRouter.delete('/', (req, res, next) => {
  res.end("删除用户");
});

app.use('/users', userRouter);

静态资源服务器

Node也可以作为静态资源服务器,并且express给我们提供了方便部署静态资源的方法;

const express = require('express');
const app = express();
app.use(express.static('./build'));
app.listen(8000, () => {
  console.log("静态服务器启动成功~");
})

错误处理方式

app.use((req, res, next) => {
  next(new Error("USER DOES NOT EXISTS"));
});
app.use((err, req, res, next) => {
  const message = err.message;
  switch (message) {
    case "USER DOES NOT EXISTS":
      res.status(400).json({message})
  }
  res.status(500)
})

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们