顯示具有 Express 標籤的文章。 顯示所有文章
顯示具有 Express 標籤的文章。 顯示所有文章

2021年1月25日 星期一

重新踏入網頁開發 (7) - React

 React - Introduction

    A JavaScript library for building user interfaces. React 在 MVC 分類上屬於 View,也就是主要用來開發前端。比起直接使用 npx create-react-app,我這裡想紀錄一些較簡單且原始的 React Sample Code。
  • 原本既有的程式碼
        <!-- Some HTML -->
        <div id="mydiv"></div>
        <!-- Some HTML -->
  • 導入 React library
        <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
  • React Code
        <script type="text/javascript">
          class HelloWorld extends React.Component {
            render() {
              return React.createElement('h1', {}, 'Hello React');
            }
          }
          const domContainer = document.querySelector('#mydiv');
          ReactDOM.render(React.createElement(HelloWorld), domContainer);
        </script>
  • Result
        <div id="mydiv">
          <h1>Hello React</h1>
        </div>

 React - JSX ver

    現今 React 大多都會用 JSX 語法,較為便捷直觀。這裡附上上面純 React 跟 React & JSX 的 Sample Code。
  <!DOCTYPE html>
  <html>
    
    <!--這兩個 script 讓我們可以在 JavaScripts 寫 React Code -->
    <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    
    <!--這個 script 讓我們可以使用 JSX 和 ES6,即使瀏覽器較舊 -->
    <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
    
    <body>

      <div id="mydiv"></div>
      <div id="mydiv_JSX_ver"></div>

      <!-- 純 React ( 不用 JSX ) -->
      <script type="text/javascript">
        class HelloWorld extends React.Component {
          render() {
            return React.createElement('h1', {}, 'Hello React');
          }
        }
        const domContainer = document.querySelector('#mydiv');
        ReactDOM.render(React.createElement(HelloWorld), domContainer);
      </script>

      <!-- JSX 版本 -->
      <script type="text/babel">
        class Hello extends React.Component {
          render() {
            return <h1>Hello React with JSX!</h1>
          }
        }
        ReactDOM.render(<Hello />, document.querySelector('#mydiv_JSX_ver'))
      </script>

    </body>

  </html>
參考資料 :

2021年1月21日 星期四

重新踏入網頁開發 (6) - Express - 5

 Express - sendFile()

    用 sendFile 把寫好的 HTML 傳出去,然後準備開始前端的開發。
    import express from 'express'
    import path from 'path';

    // 建立 express 這 module
    var app = express()
    const port = 8888
    const __dirname = path.resolve();

    // This responds a GET request for the homepage
    app.get('/', (req, res) => {
        console.log("Got a GET request for the homepage, from");
        res.sendFile(__dirname + "/hello.html");
    })

    var server = app.listen(port, function () {
    var host = server.address().address
    var port = server.address().port
        console.log("Example app listening at http://%s:%s", host, port)
    })
參考資料 :

2021年1月15日 星期五

重新踏入網頁開發 (6) - Express - 4

 Express - App v.s. Router

    Express 通常都是用 app.Method 來做 request 的 routing。而 Express 4.0 加入的 router 則可視為可以掛載的迷你 app。
    import express from 'express'

    var app = express()
    var router = express.Router() 
    const port = 8888

    // Some router level function
    function logger (req, res, next) {
        console.log('Request URL:', req.url)
        console.log('Request Type:', req.method)
        next()
    }
    function welcome (req, res) {
        res.send("Welcome to the localhost!\n")
    }
    function hello (req, res, next) {
        res.send("Hello " + req.params.userName + "\n")
        next()
    }

    router.use(logger)
    router.get('/', welcome)
    router.get('/user/:userName', hello)

    // load router,就可獲得兩個 page ( '/' 跟 '/user/:userName' )
    // 這裡要注意的是要掛載 router 的 app 要用 app.use() 而不能是 app.Method()
    // 若用 app.Method(),'/user/:userName' 就會被 app.Method() 濾掉
    // 只剩一個 page
    app.use('/', router)
    app.listen(port)
上一篇 :
參考資料 :

2021年1月14日 星期四

重新踏入網頁開發 (6) - Express - 3

 Express - Middleware

    Middleware 是會處理 req, res, next 三個物件並在 routing 時執行之 function,基本上就是 routing 時會處理的 callback function。是 Express 中蠻重要的概念。但用例子來理解比較容易。
    import express from 'express'

    // 建立 express 這 module
    var app = express()
    const port = 8888
    var userName = "Unknown"

    function hello(req, res) {
        res.send("Hello " + userName + "\n")
        res.end()
    }

    // 中間的匿名 function 就是 Middleware
    app.get('/hello/:userName.:userPassword', function (req, res, next){
        userName = req.params.userName
        console.log(userName)
        next()
    },  hello)
    
    app.listen(8888)
    所以 Express 可以用這些 Middleware 來作到流程控制,而非使用傳統的 if else。

 Express - Middleware Using

    Middleware 除了自己塞也可以有 2 種 Express 提供的方式使用。
  • Application-level
        import express from 'express'
    
        // 建立 express 這 module
        var app = express()
        const port = 8888
    
        function reqType (req, res, next){
            console.log('Request Type:', req.method)
            next()
        }
    
        function timer (req, res, next){
            var date = new Date()
            console.log('Time:', date.toString())
            if (req.params.userName == "Admin") {
                next('route') // 只能在 app.Method() 使用,在 use() 裡就會只是普通的 next()
            } else {
                next()
            }
        }
    
        function logger (req, res, next){
            console.log
            (
                'User Date:', '\n',
                'User:', req.params.userName, '\n',
                'Password:', req.params.userPassword, '\n'
            )
            res.end()
        }
    
        function warning(req, res, next) {  
            console.log("Warning: Your village is under attack\n")
            res.end()
        }
    
        // app.use() 在 route 之前,所以會先執行 use 裡的 Middleware function
        // 之後在依照 Request Method 去找相對的 app.Method() 做 Reuest Handle
        app.use('/hello/:userName.:userPassword', reqType)
    
        // 正常來講,若 Request 是 GET 且 URL 符合的話,會依照順序執行 routing function
        // 但 timer 裡有 next('route'),符合條件的話會直接把控制權交給下個 routing function,
        // 忽略它本身後面的 Middleware function,這裡就是 logger。
        app.get('/hello/:userName.:userPassword', timer, logger)
        app.get('/hello/:userName.:userPassword', warning)
        app.listen(8888)
  • Router-level
        使用方法跟 app (express()) 一模一樣,差把 app 改成 router (express.Router())
上一篇 :
下一篇 :
參考資料 :

2021年1月11日 星期一

重新踏入網頁開發 (6) - Express - 2

 Express - Route parameters

    Route parameters 可以用來擷取 URL 上的 value。
  • server.js
        import express from 'express'
    
        // 建立 express 這 module
        var app = express()
        const port = 8888
    
        // 回傳 { "userId": xxx, "bookId": xxx }
        app.get('/users/:userId/books/:bookId', function (req, res) {
            res.send(req.params)
        })
    
        // 可以用 "-" 分割,回傳 { "userId": xxx, "authorId": xxx, "bookId": xxx }
        app.get('/users/:userId-:authorId-:bookId', function (req, res) {
            res.send(req.params)
        })
    
        // 可以用 "." 分割,回傳 { "userId": xxx, "authorId": xxx, "bookId": xxx }
        app.get('/users/:userId.:authorId.:bookId', function (req, res) {
            res.send(req.params)
        })
    
        app.get('/users', function (req, res) {
            res.send("/users\n")
        })
    
        var server = app.listen(port, function () {
            var host = server.address().address
            var port = server.address().port
            console.log("Example app listening at http://%s:%s", host, port)
        })
  • Testing ( curl筆記 )
        $ curl -X GET http://localhost:8888/users/34/books/8989
        {"userId":"34","bookId":"8989"}
    
        $ curl -X GET http://localhost:8888/users/34-789-456
        {"userId":"34","authorId":"789","bookId":"456"}
    
        $ curl -X GET http://localhost:8888/users/34.123.258
        {"userId":"34","authorId":"123","bookId":"258"}
    
        $ curl -X GET http://localhost:8888/users/
        /users

 Express - Route handler

    Route handler 的 callback function 可以使用複數個,只要呼叫 next() 這個 function,便可執行下一個 callback function。
  • server.js
        import express from 'express'
    
        // 建立 express 這 module
        var app = express()
        const port = 8888
    
        // 可以塞複數個 callback, 只要確保你有傳和呼叫 next()
        app.get('/normal', function (req, res, next) {
            console.log('Hello from the first callback function!')
            next()
        }, function (req, res) {
            console.log('Hello from the second callback function!')
            res.send("Hi, this is the second callback function!\n")
            res.end()
        })
    
        // array 版
        function callbackA(req, res, next) {
            console.log('Hello from callbackA function!')
            next()
        }
        function callbackB(req, res, next) {
            console.log('Hello from callbackB function!')
            next()
        }
        function callbackC(req, res) {
            console.log('Hello from callbackC function!')
            res.send("Hi, this is callbackC!\n")
            res.end()
        }
    
        app.get('/array', [callbackA, callbackB, callbackC])
    
    
        var server = app.listen(port, function () {
            var host = server.address().address
            var port = server.address().port
            console.log("Example app listening at http://%s:%s", host, port)
        })
  • Testing - client( curl筆記 )
        $ curl -X GET http://localhost:8888/normal
        Hi, this is the second callback function!
        $ curl -X GET http://localhost:8888/array
        Hi, this is callbackC!
  • Testing - server( curl筆記 )
        $ node Learning/11.Express\&ES6/Route_handler.js 
        Example app listening at http://:::8888
        Hello from the first callback function!
        Hello from the second callback function!
        Hello from callbackA function!
        Hello from callbackB function!
        Hello from callbackC function!
上一篇 :
下一篇 :
參考資料 :

2021年1月7日 星期四

重新踏入網頁開發 (6) - Express - 1

 Express

    Fast, unopinionated, minimalist web framework for Node.js,這是 Express 的自我介紹。這裡的 unopinionated 之於 opinionated 較為信任開發者,所以你可以擁有很多作法去達到相同的目的,例如像 PERL/PHP。而 opinionated 的 software 則會只提供一個方法去達到目的,例如撰寫維基百科。沒寫過維基百科,但很顯然維基百科有他的格式存在,而格式都是維基百科的設計師所規定的。他不會讓你自由地的操作 HTML 把它當成你的部落格在寫,你只能照他的方式去更新內容。
    安裝
    npm install express

 Express - Routing

    之前 Routing 的實作是用原生 module: http、url 和自製的 dict 去實現,現在用 express 來達成。
  • server.js
       import express from 'express'
    
       // 建立 express 這 module
       var app = express()
       const port = 8888
    
       // This responds a GET request for the homepage
       app.get('/', (req, res) => {
          console.log("Got a GET request for the homepage");
          res.send('Hello GET!\n')
       })
    
       // This responds a POST request for the homepage
       app.post('/', function (req, res) {
          console.log("Got a POST request for the homepage");
          res.send('Hello POST\n');
       })
    
       // This responds a GET request for the /list_user page.
       app.get('/list_user', function (req, res) {
          console.log("Got a GET request for /list_user");
          res.send('Page Listing\n');
       })
    
       var server = app.listen(port, function () {
          var host = server.address().address
          var port = server.address().port
          console.log("Example app listening at http://%s:%s", host, port)
       })
  • Testing ( curl筆記 )
        $ curl -X GET http://localhost:8888/
        Hello GET!
        $ curl -X POST http://localhost:8888/
        Hello POST
        $ curl -X GET http://localhost:8888/list_user
        Page Listing
    第一個參數,字串支援 Regular Expression
  • server.js
       // This responds a GET request for ab*cd, abxcd, ab123cd, and so on
       app.get('/ab*cd', function(req, res) {   
          console.log("Got a GET request for /ab*cd");
          res.send('Page Pattern Match\n');
       })
    
       // This responds a GET request for book1, book2 and book3
       app.get('/book[123]', function(req, res) {   
          console.log("Got a GET request for /ab*cd");
          res.send('Page Pattern Match\n');
       })
  • Testing ( curl筆記 )
        $ curl -X GET http://localhost:8888/ab123cd
        Page Pattern Match
    
        $ curl -X GET http://localhost:8888/ab123456cd
        Page Pattern Match
    
        $ curl -X GET http://localhost:8888/book1
        Page Pattern Match
    
        $ curl -X GET http://localhost:8888/book2
        Page Pattern Match
    
        $ curl -X GET http://localhost:8888/book3
        Page Pattern Match
    
        $ curl -X GET http://localhost:8888/book4
        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="utf-8">
        <title>Error</title>
        </head>
        <body>
        <pre>Cannot GET /book4</pre>
        </body>
        </html>
上一篇 :
下一篇 :
參考資料 :


Popular Posts