10.20 Express

241 阅读1分钟

1. Express引入及安装(node web框架)

1. MVC

  • M -- Model
  • v -- View(后端渲染)
  • c -- Controller
  • 一个controller对应一个model

2. pc -- mobile

  • pc 数据和模板在服务器端合成一个数据包传回浏览器
  • mobile 前端渲染 模板一次传递 数据多次重传 渲染在前端完成
  • express+postman 测接口 json数据

3. express

  • 安装express包
    npm install -g express
    npm install express-geneator
  • 初始化文件夹
    express -e blog
    //ejs应用给express
    //experss常用模板 pug jade ejs html
    cd blog
    npm install
  • 运行
    //文件
    node ./bin/www
  • 注意
    npm install //下载package.json dependencies下所有包
    npm install md5 --save //将版本号写在package.json dependencies
    npm install md5 --save-dev //将版本号写在package.json dev-dependencies

4. express原理

5. 入口文件

  • app.js
  1. 设置全局变量和全集方法
  2. 引入路由

6. express支持模板

  • pug
  • jade
  • ejs
  • html(不建议)

7. 测接口

  • apiview
  • postman
  • github
  • gitlab

8. req.body

    exports.do_login = function (req, res, next) {
      //接收用户名和密码
      //body-parser包
      var name = req.body.username;
      var pass = req.body.pass;
    }

9. 连接数据库

mysql包

  1. mysql
    npm install mysql --save
  1. 启动mysql
  • 启动XAMpp -- mysql -- start
  • 启动navicat -- 新建连接 -- 新建数据库 -- 字符集utf8--UTF-8 Unicode -- 排序规则utf8_general_ci -- 右击运行sql文件 -- 表
  1. user.js引入
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      user     : 'me',
      password : 'secret',
      database : 'my_db'
    });
  • 接收用户名/密码
    connection.connect();
    connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
      if (error) throw error;
      console.log('The solution is: ', results[0].solution);
    });
     
    connection.end();

2. express -- request

3. express -- response

  1. res.json([status|body], [body])
  • 返回一个JSON响应.
  • res.send()的参数是一个对象或者数组的时候,会调用这个方法.
  • 当然它也在复杂的空值(null,undefined,etc),JSON转换的时候很有用,因为规范上这些对象不是合法的JSON.
    res.json(null)
    res.json({ user: 'tobi' })
    res.json(500, { error: 'message' })