Node.js学习笔记(四)

Express

  1. 起步

安装:

npm init -y 初始化项目

npm install –save express

hello world:

var express = require('express');

// 1. 创建 app
var app = express();

app.get('/',function(req,res){
    // res.write('hello ');
    // res.write('world ');
    // res.end();
    // res.end('hello world');
    res.send('hello world !');
})

app.get('/login',function(req,res){
    res.send('login !');
})

app.listen(3000,function(){
    console.log('app is running port 3000');
});

基本路由:

  • 路由
    • 请求方法
    • 请求路径
    • 请求处理函数

get:

# 当你以GET方法请求/的时候,执行对应的处理函数
app.get('/login',function(req,res){
    res.send('login !');
})

post:

# 当你以POST方法请求/的时候,执行对应的处理函数
app.post('/',function(req,res){
    res.send('login !');
})
  1. 修改完代码自动重启

我们这里使用一个第三方命令行工具:nodemon来解决频繁修改代码重启服务器问题。

nodemon是一个基于Node.js开发的一个第三方命令行工具,我们使用的时候需要独立安装

在任意目录执行该命令都可以:

npm install –global nodemon

nodemon –version

安装完毕之后,使用:

node app.js
# 使用nodemon
nodemon app.js

只要通过nodemon app.js启动的服务,则它会监视你的文件变化,当文件发生变化时候,自动帮你重启服务器。

  1. 静态服务

    // 当以/public/ 开头的时候,去./public/目录中找对应的资源
    // app.use(‘/public/’,express.static(‘./public/’));

    // 必须是/a/public目录中的资源具体路径,别名
    // app.use(‘/a/’,express.static(‘./public/’));

    // 当省略第一个参数的时候,则可以通过省略 /public的方式直接访问
    app.use(express.static(‘./public/’));

  2. 在Express中配置art-template

安装:

npm install --save art-template
npm install --save express-art-template

配置:

# 第一个参数:表示,当渲染以.art结尾的文件时候,使用art-template模板引擎
# express-art-template是专门用来在Express中把art-template整合到Express中
# express-art-template 依赖了 art-template
app.engine('art', require('express-art-template'));

使用:

# render方法默认是不可以使用,但是如果配置了模板引擎就可以使用了
# res.render('html模板名',{模板数据})
# 第一个参数不能写路径,默认会去项目中的views目录查找模板文件
# express有一个约定:开发人员吧所有的视图文件都放到了views目录中
app.get('/', function (req, res) {
    res.render('index.art', {  // 如果使用index.html格式的,应该将上面的art换成html
        user: {
            name: 'aui',
            tags: ['art', 'template', 'nodejs']
        }
    });
});

如果希望修改默认的views视图渲染存储目录,可以:

# 注意: 第一个参数不能写错
app.set('views',目录路径);
  1. 在Express中获取表单GET请求参数

Express内置了一个API,可以直接通过req.query来获取

req.query

  1. 在Express中获取表单POST请求体数据

在Express中没有内置获取表单POST请求体的API,这里我们需要使用一个第三方包:body-parser。

安装:

npm install --save body-parser

配置:

var express = require('express');
// 引包
var bodyParser = require('body-parser');

var app = express();

// 配置body-parser
// 只要加入这个配置,则在req请求对象上会多出来一个属性:body
// 也就是说你就可以直接通过req.body来获取表单POST请求体数据了
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false}));
// parse application/json
app.use(bodyParser.json())

使用:

app.use(function(req,res){
    res.setHeader('Content-Type','text/plain');
    res.write('you posted:\n')
        // 可以通过 req.body 来获取表单POST请求提数据
    res.end(JSON.stringify(req.body,null,2))
})

Express - crud

起步

  • 初始化
  • 模板处理

路由设计

请求方法 请求路径 get参数 post参数 备注
GET /students 渲染首页
GET /students/new 渲染添加学生叶页面
POST /students name,age,gender,hobbies 处理添加学生请求
GET /students/edit id 渲染编辑页面
POST /students/edit id,name,age,gender,hobbies 处理编辑请求
GET /students/delete id 处理删除请求

提取路由模块

router.js

/**
 * router.js 路由模块
 * 职责:
 *      处理路由
 *      根据不同的请求方法+请求路径设置具体请求函数
 */

var fs = require('fs')

// Express提供了一种更好的方式
// 专门用来包装路由的
var express = require('express');

// 1. 创建一个路由容器
var router = express.Router()
// 2. 把路由都挂载到 router 路由容器中

router.get('/students',function(req,res){
    fs.readFile('./db.json','utf8',function(err,data){
        if(err){
            return res.status(500).send('Server error.');
        }
        // console.log(data);
        var students = JSON.parse(data).students 
        res.render('index.html',{
            fruits: [
                '苹果',
                '香蕉',
                '橘子'
            ],
            students: students
        })
    })
})

router.get('/students/new',function(req,res){
    res.render('new.html');
})

router.post('/students/new',function(req,res){
    // 1. 获取表单数据
    // 2. 处理 将数据保存到db.json文件中用以持久化
    // 3. 发送响应
    //      先读取出来,转成对象
    //      往对象中push数据
    //      将对象转换为字符串
    //      然后把字符串再次写入文件
    console.log(req.body);
})

router.get('/students/edit',function(req,res){

})

router.post('/students/edit',function(req,res){

})

router.get('/students/delete',function(req,res){

})

// 3. 把router导出
module.exports = router

app.js:

var router = require('./router')
// 把路由容器挂载到 app 服务中
app.use(router)

设计操作学生的API

/**
 * 数据操作文件模块
 * 职责:操作文件中的数据,只处理数据,不关心业务
 */

var dbPath = './db.json'
var fs = require('fs')

/**
 * 获取所有学生列表
 * return []
 */
exports.find = function(callback){

}

exports.findById = function(id,callback){

}

/**
 * 添加保存学生
 */
exports.save = function(student,callback){

}
/**
 * 更新学生
 */
exports.updateById = function(student,callback){

}
/**
 * 删除学生
 */
exports.deleteById = function(id,callback){

}

自己编写步骤

  • 处理模板
  • 配置开放静态资源
  • 配置模板引擎
  • 简单路由:/students渲染静态页出来
  • 路由设计
  • 提取路由模块
  • 由于接下来一系列的业务操作都需要处理文件数据,需要封装student.js
  • 先写好student.js文件结构
    • 查询所有学生列表的API find
    • findById
    • save
  • 实现具体功能
    • 通过路由收到请求
    • 接收请求中的数据(get,post)
    • req.query
    • req.body
    • 调用数据操作API处理数据
    • 根据操作结果给客户端发送响应
  • 业务功能列表
    • 列表
    • 添加
    • 编辑
    • 删除

猜你喜欢

转载自blog.csdn.net/yw00yw/article/details/81676317