zoukankan      html  css  js  c++  java
  • [Express] Level 2: Middleware -- 1

    Mounting Middleware

    Given an application instance is set to the app variable, which of the following function calls would you use to mount a middleware called logger ?

    Answer: 

    app.use(logger);

    Default Middleware

    What is the only middleware that's shipped with Express 4?

    Answer: express-static

    Express Static

    Change the code in app.js to use the express-static middleware instead of the response.sendFile() function.

    var express = require('express');
    var app = express();
    
    app.get('/', function (request, response) {
      response.sendFile(__dirname + '/public/index.html');
    });
    
    app.get('/cities', function(req, res){
      var cities = ['Lotopia', 'Caspiana', 'Indigo'];
      res.send(cities);
    });
    
    app.listen(3001);

    Remove our app.get() containing the root '/' route.

    Mount the static middleware and serve files under the public directory.

    Answer:

    var express = require('express');
    var app = express();
    
    /*app.get('/', function (request, response) {
      response.sendFile(__dirname + '/public/index.html');
    });*/
    
    //cd public
    app.use(express.static('public'));
    
    app.get('/cities', function(req, res){
      var cities = ['Lotopia', 'Caspiana', 'Indigo'];
      res.send(cities);
    });
    
    app.listen(3001);

     Script Tags

    Now we can add some client side javascript by including thejquery.js and client.js files.

    Within index.html, include jquery.js using a <script> tag.

    Within index.html, include client.js using a <script> tag.

    Now in the client.js file, complete the code for the $.get function so that it calls the /cities URL path, and then runs the appendToList function.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Cities</title>
    </head>
    <body>
      <h1>Cities</h1>
    
      <ul class='city-list'></ul>
       <script src="jquery.js"></script>
       <script src="client.js"></script>
    </body>
    </html>

    Now in the client.js file, complete the code for the $.get function so that it calls the /cities URL path, and then runs the appendToList function.

    $(function(){
    
      $.get('/cities', appendToList ); 
    
      function appendToList(cities) {
        var list = [];
        for(var i in cities){
          list.push($('<li>', { text: cities[i] }));
        }
        $('.city-list').append(list);
      }
    });
  • 相关阅读:
    在python3.x上安装suds 并访问webservice
    numpy nonzero与isnan
    彻底弄清python的切片
    pandas read_sql与read_sql_table、read_sql_query 的区别
    dataframe to sql
    同时替换掉多个字符串
    matplotlib中在for中画出多张图
    MySql 创建/删除数据库
    python3与anaconda2共存
    js调用打印机
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4141908.html
Copyright © 2011-2022 走看看