NodeJS express

express

基于Nodejs Web 的开发框架(老框架了 目前无人维护)

其他框架:Koa、egg

express快速入门

1.创建一个空的文件夹,作为项目

2.初始化这个项目 npm init -y (生成版本库)

3.安装项目的依赖模块 npm install --save express

4.git管理

4.1 git 初始化 git init
4.2 编辑 .gitignore(写要忽略的文件夹名)文件

5.在项目目录下创建一个 server.js 作为项目的入口文件(启动文件)

6.在入口文件中写代码

7.设置npm脚本,并启动。package.json -> scripts ->编辑key:value(要运行的代码) -> 启动:npm run key(key脚本名为start时run可忽略)

基于express快速搭建 后台服务

1.引入express模块

2.调用express方法,生成express实例对象

3.设置路由,来响应不同的url地址请求

路由:一个url地址对应一个不同的路由处理程序(不同的url地址有不同的回调函数去响应)

4.监听端口号

const express = require('express'); //1
const server = express(); //2

server.get('/',(req,res) => { //3
    res.send('express 搭建后台服务');
});

server.listen(3000); //4

express 路由

语法:app.methods(path,callback)

  • app 是 express 实例对象
  • methods 是请求方法 get | post | put | update | delete |...
  • path 就是路径(url定值的 pathname ),必须以'/'开头
  • callback 回调函数,路由的处理函数
    • req
    • res (这里的 req res 就是原生nodejs中的 req res。但比原生中要多一些属性方法,是express加上去的)
    • next 是一个方法,调用这个方法会让路由继续匹配下一个能匹配上的

重点:

1.路由代码与 http 请求地址的对应关系

// GET http://localhost:3000/
server.get('/',(req,res) => {res.send('hello express') })

// GET http://localhost:3000/abc
server.get('/abc',(req,res) => {res.send('hello abc') })
  1. 如果有多个相同路径的路由,那么会按照书写顺序执行第一个
// GET http://localhost:3000/
server.get('/a',(req,res) => {res.send('hello') })

// GET http://localhost:3000/abc
server.get('/b',(req,res) => {res.send('world') })

//输出hello

可以让他按照顺序找到写一个匹配的路由 next()

// GET http://localhost:3000/
server.get('/abc',(req,res,next) => {
    console.log('hello');
    res.send('hello');
    next(); //继续往下寻找匹配的路由
    
})

// GET http://localhost:3000/abc
server.get('/abc',(req,res) => {
    console.log('world'); //控制台会输出
    res.send('world'); //报错 上面已关闭请求
})

express 中 request(请求) 与 response(响应) (了解这两个对象中被 express 增加的常用属性和方法)

request(请求)

  • req.query : 获取get请求传递过来的参数(url的查询参数串)
console.log(req.query); //{ name: 'vvv', age: '12' }
  • req.body : 获取post请求传递过来的参数
    • 需要设置 express.json 和 express.urlencoded 这两个中间件
//设置中间件
server.use(express.json());
server.use(express.urlencoded({extended:true}));

server.post('/',(req,res) => {
    console.log(req.body); //{ name: '小荟', year: '3' }
    res.send('xiaohui');
});
  • req.cookies : 获取浏览器传递过来的Cookies
    • 需要使用 cookie-parser 中间件
    • 1.安装 cookie-parser npm install --save cookie-parser
    • 2.在server.js中 引入cookie-parser模块
    • 3.在server.js中 使用cookie-parser
//获取cookie req.cookies
const cookieParser = require('cookie-parser'); //引入模块
server.use(cookieParser());  //设置中间件
server.get('/getcookie',(req,res) => {
    console.log(req.cookies); 
    res.send('cookie获取成功');
});
  • req.get() 获取指定的HTTP的请求头
server.get('/',(req,res) => {
    console.log(req.get('Host'));  //localhost:3000
    res.send('获取指定的HTTP请求头');
});
  • req.params 获取路由的动态参数parameters (输出对象)
server.get('/:id',(req,res) => {  // GET http://localhost:3000/a    :id 动态路由参数 可匹配任意 可设置多个
    console.log(req.params); //{ id: 'a' }
    res.send('req.params 获取路由的动态参数');
});
  • req.hostname/req.ip : 获取主机名和IP地址
server.get('/',(req,res) => { 
    console.log(req.hostname); //localhost
    console.log(req.ip); //::1
    res.send('req.hostname 获取主机名和IP地址'); 
});
  • req.path : 获取请求路径
server.get('/a',(req,res) => {
    console.log(req.path);  // /a
    res.send('req.path 获取请求路径');
});
  • req.protocol : 获取协议类型

response(响应)

  • res.cookie(name,value,[option]) : 设置Cookie
//设置cookie
server.get('/setcookie',(req,res) => {
    res.cookie('name','女',{  //'name'不能为中文  {}cookie的选项对象 maxAge cookie保存的时间
        maxAge : 1000*60*10
    });
    res.send('cookie设置成功');
});
  • res.clearCookie() : 清除cookie

  • res.set : 设置HTTP响应头,传入object可以一次设置多个头

  • res.status : 设置HTTP状态码

server.get('/',(req,res) => {
    res.set({'name':'xiaohui','age':18});
    res.status(505).send('res.set 设置HTTP响应头');
});
  • res.send() : 传送HTTP响应
  • res.redirect : 重定向到明确的路径,需要有明确的HTTP status代码,如果没有,默认status代码为 ‘302’ ‘Found’(页面跳转)
  • res.json : 传送JSON响应 :可传送对象 对象可转成json的格式
  • res.download() : 传送指定路径的文件
  • res.sendFile(path,[option],[fn]) : 通过给定的路径传递文件,通过文件的扩展名设置响应头Content-Type。除非root选项已经在参数options中设置了,path必须是绝对路径
  • res.render(view,[locals],[callback]) : 渲染视图模板。渲染一个视图,并把一个HTML字符串发送给客户端,locals是一个对象,其属性定义了视图内的局部变量。callback是一个回调函数,如果提供了,这个方法返回可能的错误信息和渲染字符串。如果有错误,这个方法会使用一个next(err)的内部函数

express 静态资源托管

通过 express 让某个 url 输出HTML页面

1.读文件

  • fs.readFileSyne('文件路径'); //读出来的是buffer 会下载
    • ①转字符串 toString res.set('Content-Type','text/html; charset=utf-8'); //设置响应头使浏览器输出HTML
    • ②直接使用 res.sendFile('需要渲染的页面路径[绝对路径]'); path.resolve(__dirname,'');
server.get('/',(req,res) => {
    let data = fs.readFileSync('./index/index.html');
    console.log(data.toString());
    res.set('Content-Type','text/html;charset=utf-8');

    // res.sendFile(path.resolve(__dirname,'./index/index.html'));
});

使用 res.sendFile 每次引入不同文件都需要创建一个路由 太麻烦,需要静态资源托管
静态资源托管:将项目下的某个文件夹作为静态资源托管的文件夹,后续只要想访问这个文件夹的资源,都可通过某种规则的路径来访问

  • 配置静态资源托管的文件夹
//http://localhost:3000/
 app.use(express.static(path.resolve(__dirname,'./public')));  //app为express实例 use使用中间件
 //这时可将public文件看成web服务的根目录 ./
 //http://localhost:3000/css/style.css
  • 也可通过设置来修改静态资源托管的根路径 app.use
//http://localhost:3000/static
 app.use('/static',express.static(path.resolve(__dirname,'./public')));

express 中间件

  1. express.json()
  2. express.urlencode() (req.body)
  3. cookieParser()
  4. express.static()

中间件其实是一个携带req、res、next这三个参数的函数,在请求与响应之间做一些中间处理的代码

//定义一个中间件函数
const name = (req,res,next) => {
    //需要做的事
    next();
};

server.use(name); //调用这个中间件
  • 注意

    • 中间件函数,在做完事情之后,必须调用 next() 否则程序不会往下走

    • 中间件函数的调用必须放在需要使用的函数的前面

一、 实现一个日志输出的中间件
在这个项目中所有的请求,都要输出一个日志。日志包含请求机器的IP地址、请求路径、请求时间

// 自己实现一个中间件,中间件其实就是一个函数,携带者 req | res | next 这三个参数的函数
// 1. 定义这样的一个中间件函数出来
const logger = (req, res, next) => {
  console.log(
    `请求的ip地址是:${req.ip}, 请求的路径是:${
      req.url
    }, 请求的时间是:${new Date().getTime()}`
  );
  next();
};
// 2. 使用 server.use() 调用这个中间件 use 方法需要接受的是一个携带了 req| res| next 的函数
server.use(logger);
//在这个代码后面的请求都能使用上这个中间件

中间件可以重写 req、res 在其上面添加属性方法

二、实现一个让每个路由身上都能访问到 req.requestTime 的中间件

const helloWorld = (req, res, next) => {
  req.requestTime = new Date().getTime();
  next();
};

server.use(helloWorld);

三、思考实现一个cookieParser() 中间件 定义方法 给req加cookie(先得到cookie) cookie会随http的请求携带在请求头上 req.get 获取指定的HTTP的请求头->拆分成对象->写入res的对象上

  1. req.get('Cookies') 请求头中的数据
  2. req.cookies = 1中拿出的数据经过转化成的对象

四、可配置的中间件
希望这个中间件能够通过不同的设置,让其 requestTime 是一个不同的格式
比如:1. 时间戳 2. 年份 3. 月份

const helloWorld = num => { //num 配置的参数
  return (req, res, next) => { //闭包
    let date = new Date();
    if (num === 1) {
      req.requestTime = date.getTime();
    }
    if (num === 2) {
      req.requestTime = date.getFullYear();
    }
    if (num === 3) {
      req.requestTime = date.getMonth();
    }
    next();
  };
};

server.use(helloWorld(3));
  • use 是全局中间件的设置
server.use(helloWorld(3));
  • 可以局部设置中间件,给具体某一个路由设置某个中间(路由可有多个callback)
server.get("/a", helloWorld(1), (req, res) => {
    console.log(req.requestTime);
    res.send("a");
  });
  
  server.get("/b", helloWorld(2), (req, res) => {
    console.log(req.requestTime);
    res.send("b");
  });
  
  server.get("/c", helloWorld(3), (req, res) => {
    console.log(req.requestTime);
    res.send("c");
  });

express 跨域

// 设置 cors 允许跨域
// 在响应头中加入一个属性 Access-Control-Allow-Origin
// 将这个属性的值设置为 *
server.use((req, res, next) => {
    res.set("Access-Control-Allow-Origin", "*");
    // ...
    next();
});

server.get("/getStudent", (req, res) => {
    res.send({
      code: 0,
      msg: "获取学生列表成功",
      data: [{ id: 1, name: "张三", age: 18 }, { id: 2, name: "李四", age: 20 }]
    });
});
  • 此处应用 live-server 工具模块 使HTML页面在后台打开

momentjs.cn - 日期时间格式化工具类

// server.use(helloWorld(2)); // YYYY-mm-dd yy-mm-dd hh:mm:ss

  1. npm install --save moment
  2. 引入并使用
const moment = require('moment');
const helloWorld = str => {
    return (req, res, next) => {
      req.requestTime = moment().format(str);
      next();
    };
};

server.get("/a", helloWorld("YYYY-MM-DD"), (req, res) => {
    console.log(req.requestTime);
    res.send("a");
});

服务端打开html页面

live-server 一个 nodejs d 的工具模块,能快速的帮我们将某个文件夹作为web服务的根目录文件夹,并且以 localhost:8080 端口监听

1.全局安装 npm install -g live-server
2.在某个文件夹下面,使用 live-server 这个命令即可

你可能感兴趣的:(NodeJS express)