当前位置: 首页>前端>正文

express怎么封装 express软件怎么用

1、安装express

首先,可以通过npm或者淘宝镜像cnpm全局安装express框架

使用npm

npm install -g express

使用cnpm
一、安装淘宝镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
二、安装express(-g : 全局安装, --save : 将其保存到依赖列表中)
cnpm install express

2、express的特点

1.实现了路由功能
2.中间件功能
3.扩展了req和res对象
4.可以集成其他模版引擎

3、简单实例

//引入express
const express = require('express');

//创建一个app对象(类似于server的对象)
var app = express();

//注册路由(这里只能监听get方法和根目录)
app.get('/', function (req, res) {
    res.send('indexPage');
})

//启动服务
app.listen(3000,function(){
    console.log('服务器连接成功');
})

浏览器访问http://localhost:3000 页面显示indexPage
访问其他路径的时候,虽然并没有设置响应内容,但是服务器并不会报错,页面会显示
Cannot GET /aaaa

4、res.send()与res.end()

  • res.end()参数类型只能接收字符串和Buffer
  • res.send()参数类型除了能接收字符串和Buffer,还可以接收数组或者对象
  • res.send()会自动发送更多的响应报文头,例如设置content-Type为utf-8,所以中文也没有乱码

5、app.get和app.post,app.use,app.all注册路由的区别

  • app.get注册路由
    请求方法必须是get方法,而且路径是严格匹配的(忽略url后面拼接的参数,例如?name=123这类)
  • app.post注册路由
    请求方法必须是post方法,而且路径是严格匹配的
  • app.use注册路由
    不限定请求的方法,get/post等都可以
    路径模糊匹配,这个路径和他路径下的子路径都可以匹配
app.use('/item', function (req, res) {
    res.send('itemPage');
})
//http://localhost:8080/item 成功
//http://localhost:8080/item/233 成功
//http://localhost:8080/item?name=hello 成功
//http://localhost:8080/123/item 失败
//http://localhost:8080/item233 失败
  • app.all注册路由
    不限定请求的方法,但是请求路径要求严格匹配

6、中间件

1. 补充框架功能
2. 重用   分工  流水线  next  顺序

// app.use 也是一个中间件
app.use(express.static('./public'));   // 静态文件伺服能力
// express中所有的路由即中间件
app.get('/yundingshuyuan', function(req, res, next) {
	res.send('云顶书院官网');
})
app.post('/get', function (req, res, next) {
	console.log('这是第一个post请求');
	next();    // 中间件提供了next()方法,当前中间件工作完成之后,通知下一个中间件执行。
})
app.post('/get', function (req, res, next) {
	console.log('这是第二个post请求');
})

// 当浏览器请求/get路径时,终端会输出 
// 这是第一个post请求
// 这是第二个post请求

顺便说一下接口是什么

软件接口的定义

接口(软件类接口)是指对协定进行定义的引用类型。其他类型实现接口,以保证它们支持某些操作。接口指定必须由类提供的成员或实现它的其他接口。与类相似,接口可以包含方法、属性、索引器和事件作为成员

express怎么封装 express软件怎么用,express怎么封装 express软件怎么用_express怎么封装,第1张

nodejs接口是使用nodejs实现的包含方法、属性、索引器和事件作为成员对协定进行定义的引用类型。

可以用express模块来写接口

var express=require('express');
var app=express();
 
// 定义接口
app.get('/yundingshuyuan/:name',function(req, res) {
    res.send(req.params);
})

// 定义接口
app.post('/yundingchengyuan', function(req, res) {
    // 获取前端传回的数据以及具体操作
    res.send('post');
})

app.listen(3000,function(){
    console.log('服务器连接成功');
})
调用接口:localhost:3000/yundingshuyuan/litao

以上是我学习express基础的部分笔记,希望对大家有所帮助。



https://www.xamrdz.com/web/28j1933122.html

相关文章: