美文网首页Node.js让前端飞
node.js Web应用开发框架Express

node.js Web应用开发框架Express

作者: 风慕李 | 来源:发表于2017-12-12 09:11 被阅读31次

    Express提供了帮你创建各种Web应用的一系列强大特性,可以帮你快速搭建完整功能的网站。

    安装Express

    Express安装之前,需要介绍与之相关的三个重要模块:

    1. body-parser:node.js中间件,用于处理JSON,Text,和URL编码的数据
    2. cookie-parser:cookie解析工具,可将req.cookies取到的cookie转成对象
    3. multer:node.js中间件,用于处理enctype="multipart/form-data"的表单数据。
    G:\node\node-Express> npm install express --save
    G:\node\node-Express> npm install body-parser --save
    G:\node\node-Express> npm install cookie-parser --save
    G:\node\node-Express> npm install multer --save
    

    关于node.js RESTful API这篇文章中就已经用到了Express相关知识。关于Express详细介绍请看Express 4.x API 中文手册

    Express应用使用回调函数的参数(request,response)对象来处理请求和响应的数据,他们所包含的对象属性的方法含义请参见RequestResponse

    静态文件

    新建static文件,其中建立images文件放入一张图片,建立node-static.js,复制黏贴如下代码:

    var express = require('express');
    var app = express();
     
    app.use(express.static('static'));
     
    app.get('/', function (req, res) {
       res.send('静态文件');
    })
     
    var server = app.listen(4321, function () {
      var host = server.address().address
      var port = server.address().port
      console.log("访问地址为 http://%s:%s", host, port)
     
    })
    浏览器中输入 localhost:4321/images/timg.jpg就可访问到这张图片了。
    

    接下来我们在表单中通过GET、POST方法分别提交两个参数。首先建立form.html,其中复制黏贴如下代码:

    <html>
    <body>
        <form action="http://127.0.0.1:4321/get-data" method="GET">
            Author:
            <input type="text" name="author">
            <br> Description:
            <input type="text" name="description">
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
    
    GET方法
    node-get.js代码
    ---
    var express = require('express');
    var app = express();
    app.use(express.static('static'));
    app.get('/form.html', function (req, res) {
       res.sendFile( __dirname + "/" + "form.html");
    })
     
    app.get('/get-data',function (req, res) {
        //设置编码格式
        res.set('Content-Type', 'text/html');
       // 输出 JSON 格式
       var response = {
           "first_name":req.query.author,
           "last_name":req.query.description
       };
       console.log(response);
       res.end(JSON.stringify(response));
    })
     
    var server = app.listen(4321, function () {
      var host = server.address().address
      var port = server.address().port
     
      console.log("访问地址为 http://%s:%s", host, port)
     
    })
    ---
    G:\node\node-Express> node node-get.js
    访问地址为 http://:::4321
    浏览器中输入localhost:4321/form.html,填写表单提交
    { first_name: '风慕李', last_name: '12345' }
    
    POST方法(记得对form.html做相应的更改)
    node-post.js代码:
    ---
    var express = require('express');
    var app = express();
    var bodyParser = require('body-parser');
     
    // 创建 application/x-www-form-urlencoded 编码解析
    var urlencodedParser = bodyParser.urlencoded({ extended: false })
    //  这里需要将form.html中action路径修改,method方式修改下
    app.use(express.static('static')); 
    app.get('/form.html', function (req, res) {
       res.sendFile( __dirname + "/" + "form.html" );
    }) 
    app.post('/post-data', urlencodedParser, function (req, res) {     
        res.set('Content-Type', 'text/html; charset=UTF-8');
       // 输出 JSON 格式
       var response = {
           "author":req.body.author,
           "description":req.body.description
       };
       console.log(response);
       res.end(JSON.stringify(response));
    })
     
    var server = app.listen(4321, function () { 
      var host = server.address().address
      var port = server.address().port 
      console.log("访问地址为 http://%s:%s", host, port)
     
    })
    ---
    G:\node\node-Express> node node-post.js
    访问地址为 http://:::4321
    浏览器中输入localhost:4321/form.html,填写表单提交
    { author: 'fengml', description: '风慕李' }
    
    文件上传
    upload.html代码:
    ---
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        </head>
        <body>
            选择一个文件上传: <br />
            <form action="/upload" method="post" enctype="multipart/form-data">
                <input type="file" name="image" size="50" />
                <br />
                <input type="submit" value="上传" />
            </form>
        </body>
    </html>
    
    node-upload.js代码:
    ---
    var express = require('express');
    var app = express();
    var fs = require("fs"); 
    var bodyParser = require('body-parser');
    var multer  = require('multer'); 
    app.use(express.static('static'));
    // 创建 application/x-www-form-urlencoded 编码解析
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(multer({ dest: '/tmp/'}).array('image'));
     
    app.get('/upload.html', function (req, res) {
       res.sendFile( __dirname + "/" + "upload.html" );
    })
     
    app.post('/upload', function (req, res) { 
       console.log(req.files[0]);  // 上传的文件信息 
       var des_file = __dirname + "/" + req.files[0].originalname;
       fs.readFile( req.files[0].path, function (err, data) {
            fs.writeFile(des_file, data, function (err) {
             if( err ){
                  console.log( err );
             }else{
                   response = {
                       message:'upload success', 
                       filename:req.files[0].originalname
                  };
              }
              console.log( response );
              res.end( JSON.stringify( response ) );
           });
       });
    })
     
    var server = app.listen(4321, function () {
     
      var host = server.address().address
      var port = server.address().port
     
      console.log("访问地址为 http://%s:%s", host, port)
     
    })
    
    cookie
    <!--res.cookie('author', 'authorCookie', { domain: '.xxx.com', path: '/xx', secure: true, expires: new Date(Date.now() + 900000), httpOnly: true ,maxAge: 900000,signed: true });-->
    
    header 1 | header 2
    ---|---
    row 1 col 1 | row 1 col 2
    row 2 col 1 | row 2 col 2
    
    
    ---
    var express = require('express');
    var cookieParser = require('cookie-parser');
    var app = express();
    app.use(cookieParser());
    
    // 获取cookie记录
    app.get('/',function (req,res) {
        var arr = [];
        for (var key in req.cookies){
            for(var i = 0;i < req.cookies[key].length;i++){
                arr.push(decodeURI(req.cookies[key][i]))
            }
        }
        res.send('浏览记录' + arr)
    })
    // 存储cookie  eg:http://127.0.0.1:4321/author?author=风慕李
    app.get('/author',function (req,res) {
        // 获取作者名字
        res.set('Content-Type', 'text/html; charset=UTF-8');
        var author = encodeURI(req.query.author);
        // 读取该author的cookie值
        var authorCookie = req.cookies.author || [];
        authorCookie.push(author)
        // maxAge失效时间 以毫秒为单位
        res.cookie(author,authorCookie,{maxAge:15 * 60 * 1000,httpOnly:true})
        res.send(decodeURI(author) + '你好')
    })
    app.listen(4321);
    
    G:\node\node-Express> node node-cookie.js
    浏览器先后访问localhost:4321  localhost:4321/author?author=风慕李,查看结果
    

    原文地址 https://gitee.com/wangFengJ/node/tree/master/node-Express

    相关文章

      网友评论

        本文标题:node.js Web应用开发框架Express

        本文链接:https://www.haomeiwen.com/subject/kadgixtx.html