zoukankan      html  css  js  c++  java
  • express笔记

    在koa出世之前,express是最流行的且少数可选的nodejs web框架,现在出到4.x了,今天决定学一下,至少知道怎么用。

    首先梳理一下大致的脉络:

    express是一个基于nodejs 的web应用框架,真的很轻巧灵活,它在底层对node的http模块进行了封装,使我们能很轻易地处理web请求/响应.。

    express的灵活还体现在,我们可以通过中间件来对请求进行定制化处理。中间件其实就是封装了特定功能的代码片段,在执行response之前,对request进行特定的处理。

    express有完善的第三方插件,帮助我们实现服务器的各种功能。

    1.安装:

    npm install express --save

    2.最基本使用:

     1 const express = require('express')
     2 const app = express()
     3 
     4 app.get('/', function (req, res) {
     5   res.send('Hello World!')
     6 })
     7 
     8 app.listen(3000, function () {
     9   console.log('Example app listening on port 3000!')
    10 })

    引入并创建一个express实例app,app可以调用各种express封装好的方法,像get、post等,沿袭了nodejs事件回调的代码风格,乍一看,其实和nodejs的写http服务器差不多。

    事实上就是如此。毕竟express的方法就是基于node的各种api,但express的封装让我嗯可以更专注在服务器逻辑上。

    3.应用生成工具:express-generator (自带命令集)

    npm install express-generator -g

    安装完后,express可以使用express-generator带来的命令行。输入 express -h ,回车,会罗列出相关命令行。

    输入以下命令可以在当前文件夹下创建项目文件夹(骨架)。

    express --view=pug myapp

    进入该文件夹目录,执行npm install安装相关依赖,再输入:

    set DEBUG=myapp:* & npm start

    生成的项目默认监听3000端口。

    ********************************分割线*********************************

    4.路由

    在单页面应用中,路由是url改变时,显示相应的内容。

    express中的路由类似。当请求的method和路径匹配时,对该请求进行处理。

    app.METHOD(PATH, HANDLER)  //路由的结构

    所以,所谓路由本质上就是一个个处理请求的函数:

     1 app.get('/', function (req, res) {
     2   res.send('Hello World!')
     3 })
     4 
     5 app.post('/', function (req, res) {
     6   res.send('Got a POST request')
     7 })
     8 
     9 //注意,all并不特定于任何http方法,.all()是用来加载中间件函数的,可用于任何请求类型
    10 app.all('/secret', function (req, res, next) {
    11   console.log('Accessing the secret section ...')
    12   next() // pass control to the next handler
    13 })

    这是最近基本的路由方法。express中,路由路径(route path)的审验可以使用regexp,查询字符串不属于路由路径。而且路由路径可以使用路由参数如:

    1 app.get('/users/:userId/books/:bookId', function (req, res) {
    2   res.send(req.params)
    3 })

    另外路由处理函数可以有多个:

     1 app.get('/example/b', function (req, res, next) {
     2   console.log('the response will be sent by the next function ...')
     3   next()
     4 }, function (req, res) {
     5   res.send('Hello from B!')
     6 })
     7 
     8 //使用数组方式
     9 var cb0 = function (req, res, next) {
    10   console.log('CB0')
    11   next()
    12 }
    13 
    14 var cb1 = function (req, res, next) {
    15   console.log('CB1')
    16   next()
    17 }
    18 
    19 var cb2 = function (req, res) {
    20   res.send('Hello from C!')
    21 }
    22 
    23 app.get('/example/c', [cb0, cb1, cb2])

    路由比较常用的方式因该是利用express.router()返回的router模块:

    var express = require('express')
    var router = express.Router()
    
    // middleware that is specific to this router
    router.use(function timeLog (req, res, next) {
      console.log('Time: ', Date.now())
      next()
    })
    // define the home page route
    router.get('/', function (req, res) {
      res.send('Birds home page')
    })
    // define the about route
    router.get('/about', function (req, res) {
      res.send('About birds')
    })
    
    module.exports = router

    然后在另一个文件中引用该模块,该模块作为一个中间件:

    var birds = require('./birds')
    
    // ...
    
    app.use('/birds', birds)

    当请求的地址匹配到‘/bird’或'/bird/about'时,调用对应的回调。

    更多细节可看文档:http://expressjs.com/en/guide/routing.html

    5.设置静态文件:express.static(PATH)

    Express 提供了内置的中间件 express.static 来设置静态文件夹.用来自行响应客户端的静态资源请求。

    1  app.use(express.static('public'))
    2  //如果想将服务器上该资源文件夹挂到一个虚拟路径,使用
    3  app.use('/static', express.static('public'))
    4  //更妥当的方式
    5  app.use('/static', express.static(path.join(__dirname, 'public')))

     代码第一行中'public'是项目中的一个文件夹,发布的静态资源都放在里边。public一般意义上是客户端访问到的根目录,即www.xxx.com/

    6.文件上传

    在nodejs中,文件上传会使用一个formidable插件来实现();

    但是在express中,则是使用一个插件multer,我们要做的只是简单的读取并写到磁盘中的指定位置即可。

    1 var multer  = require('multer');
    2 //注意,array()中的字符参数是file input的name属性
    3 app.use(multer({ dest: '/tmp/'}).array('image'));
     1 app.post('/file_upload', function (req, res) {
     2  
     3    console.log(req.files[0]);  // 上传的文件信息
     4  
     5    var des_file = __dirname + "/" + req.files[0].originalname;
     6    fs.readFile( req.files[0].path, function (err, data) {
     7         fs.writeFile(des_file, data, function (err) {
     8          if( err ){
     9               console.log( err );
    10          }else{
    11                response = {
    12                    message:'File uploaded successfully', 
    13                    filename:req.files[0].originalname
    14               };
    15           }
    16           console.log( response );
    17           res.end( JSON.stringify( response ) );
    18        });
    19    });
    20 })

     multer插件的使用详见:https://github.com/expressjs/multer

    7.cookie处理

    我们可以使用中间件获取cookie信息:

     1 var express      = require('express')
     2 var cookieParser = require('cookie-parser')
     3  
     4 var app = express()
     5 app.use(cookieParser())
     6  
     7 app.get('/', function(req, res) {
     8   console.log("Cookies: ", req.cookies)
     9 })
    10  
    11 app.listen(8081)

    8.模板引擎

  • 相关阅读:
    友链大集合
    雅礼学习10.7
    雅礼学习10.6
    雅礼学习10.5
    雅礼学习10.4
    雅礼学习10.3
    雅礼学习10.4
    雅礼学习10.2
    雅礼学习10.1
    如何让SublimeText3更好用
  • 原文地址:https://www.cnblogs.com/alan2kat/p/7624620.html
Copyright © 2011-2022 走看看