学习

  1. 文档
http://expressjs.com/

npm install express --save

  1. 开始 hello word
# express 

const express = require('express')
const app = express()
const port = 3000

// app.get('/', (req, res) => {
app.get('/', function(req, res) {
  res.send('Hello World!')
  res.end('Hello World!')  // 可以用,但是不会自动添加content-type这类优化
})

//两个send有用吗?
app.get('/a', function (req, res) {
    res.send('1')
    res.send('2') //这个不会生效
});


app.listen(port, () => {
// app.listen(port, function()  {
  console.log(`Example app listening at http://localhost:${port}`)
})



# http 
var http = require('http')

http
 .createServer(function(req,res){
    res.end('Hello World!')
 })
 .listen(3000,function(){
     console.log('running..')
 })

  1. 基本概念
# 路由
// app.get('/', (req, res) => {
app.get('/', function(req, res) {
  res.send('Hello World!')
  res.end('Hello World!')  // 可以用,但是不会自动添加content-type这类优化
})



# 静态服务
# 以 /public/ 开头的访问,去./files/目录中查找对应的资源,【127.0.0.1:3000/public/test.html】
app.use('/public/',express.static('./files/'))
# 省略第一个参数,访问的时候可以省略/public/,【127.0.0.1:3000/test.html】
app.use(express.static('./files/'))


  1. 使用express-art-template
http://aui.github.io/art-template/express/

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


# hello word
var express = require('express');
var app = express();

// view engine setup
app.engine('art', require('express-art-template'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'art');

// routes
app.get('/', function (req, res) {
    res.render('index.art', {
        user: {
            name: 'aui',
            tags: ['art', 'template', 'nodejs']
        }
    });
});
  1. 文件上传
# 普通上传
https://www.jianshu.com/p/4fd62a2c7c0a
#安装
npm install express multer

# js
var multer = require('multer');
var upload = multer({dest:'upload/'})

router.post('/upload', upload.single('myfile'), function(req, res, next){
    //console.log(req);
  res.send({ret_code: '0'});
});

# html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="myfile" id="myfile" value="" />
            <input type="submit" value="上传"/>
        </form>
    </body>
</html>

# 解决文件没有后缀名问题
var upload = multer({dest:'upload/'}) 替换成如下
var storage = multer.diskStorage({
 //设置上传后文件路径,uploads文件夹需要手动创建!!!
    destination: function (req, file, cb) {
        cb(null, './public/uploads')
   }, 
 //给上传文件重命名,获取添加后缀名
  filename: function (req, file, cb) {
      var fileFormat = (file.originalname).split(".");
      cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]);
  }
});  
//添加配置文件到muler对象。
var upload = multer({
  storage: storage
});




# 拖拽上传
https://www.cnblogs.com/JerryWang1991/p/3395536.html
https://github.com/wangyan9110/FileUploader


  1. post表单处理
需要中间件
http://expressjs.com/en/resources/middleware/body-parser.html
# 安装
npm install body-parser

# 使用
var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))

  1. 主app写法,router写法
/**
 * app.js 入门模块
 * 职责:
 *   创建服务
 *   做一些服务相关配置
 *     模板引擎
 *     body-parser 解析表单 post 请求体
 *     提供静态资源服务
 *   挂载路由
 *   监听端口启动服务
 */

var express = require('express')
var router = require('./router')
var bodyParser = require('body-parser')

var app = express()

app.use('/node_modules/', express.static('./node_modules/'))
app.use('/public/', express.static('./public/'))

app.engine('html', require('express-art-template'))

// 配置模板引擎和 body-parser 一定要在 app.use(router) 挂载路由之前
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

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

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

module.exports = app








/**
 * router.js 路由模块
 * 职责:
 *   处理路由
 *   根据不同的请求方法+请求路径设置具体的请求处理函数
 * 模块职责要单一,不要乱写
 * 我们划分模块的目的就是为了增强项目代码的可维护性
 * 提升开发效率
 */

var fs = require('fs')
var Student = require('./student')

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

// 1. 创建一个路由容器
var router = express.Router()

// 2. 把路由都挂载到 router 路由容器中

/*
 * 渲染学生列表页面
 */
router.get('/students', function (req, res) {
  Student.find(function (err, students) {
    if (err) {
      return res.status(500).send('Server error.')
    }
    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. 发送响应
  Student.save(req.body, function (err) {
    if (err) {
      return res.status(500).send('Server error.')
    }
    res.redirect('/students')
  })
})

/*
 * 渲染编辑学生页面
 */
router.get('/students/edit', function (req, res) {
  // 1. 在客户端的列表页中处理链接问题(需要有 id 参数)
  // 2. 获取要编辑的学生 id
  // 
  // 3. 渲染编辑页面
  //    根据 id 把学生信息查出来
  //    使用模板引擎渲染页面

  Student.findById(parseInt(req.query.id), function (err, student) {
    if (err) {
      return res.status(500).send('Server error.')
    }
    res.render('edit.html', {
      student: student
    })
  })
})

/*
 * 处理编辑学生
 */
router.post('/students/edit', function (req, res) {
  // 1. 获取表单数据
  //    req.body
  // 2. 更新
  //    Student.updateById()
  // 3. 发送响应
  Student.updateById(req.body, function (err) {
    if (err) {
      return res.status(500).send('Server error.')
    }
    res.redirect('/students')
  })
})

/*
 * 处理删除学生
 */
router.get('/students/delete', function (req, res) {
  // 1. 获取要删除的 id
  // 2. 根据 id 执行删除操作
  // 3. 根据操作结果发送响应数据

  Student.deleteById(req.query.id, function (err) {
    if (err) {
      return res.status(500).send('Server error.')
    }
    res.redirect('/students')
  })
})

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

// 这样也不方便
// module.exports = function (app) {
//   app.get('/students', function (req, res) {
//     // readFile 的第二个参数是可选的,传入 utf8 就是告诉它把读取到的文件直接按照 utf8 编码转成我们能认识的字符
//     // 除了这样来转换之外,也可以通过 data.toString() 的方式
//     fs.readFile('./db.json', 'utf8', function (err, data) {
//       if (err) {
//         return res.status(500).send('Server error.')
//       }

//       // 从文件中读取到的数据一定是字符串
//       // 所以这里一定要手动转成对象
//       var students = JSON.parse(data).students

//       res.render('index.html', {
//         fruits: [
//           '苹果',
//           '香蕉',
//           '橘子'
//         ],
//         students: students
//       })
//     })
//   })

//   app.get('/students/new', function (req, res) {

//   })

//   app.get('/students/new', function (req, res) {

//   })

//   app.get('/students/new', function (req, res) {

//   })

//   app.get('/students/new', function (req, res) {

//   })

//   app.get('/students/new', function (req, res) {

//   })
// }


原文地址:https://www.cnblogs.com/amize/p/14885822.html