2020年10月29日 星期四

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

Route ( URL )

    通過不同的 URL 去區別不同請求
  • Server.js
        import http from 'http'
        import url from 'url'
    
        function onRequest(request, response) {
            // 會紀錄 request url
            var path_name = url.parse(request.url).pathname;
            console.log("Request for " + path_name + " received");
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.write("Hello World.\n");
            response.end();
        }
    
        http.createServer(onRequest).listen(8888);
        console.log("Server has started...");
  • 用 curl 去 request
        $ curl http://localhost:8888/
        Hello World.
        $ curl http://localhost:8888/students/1
        Hello World.
  • 伺服器端顯示
        $ node Server.js 
        Server has started...
        Request for / received
        Request for /students/1 received
上一篇 :
下一篇 :
參考資料 :

Related Posts:

  • 重新踏入網頁開發 (7) - React  React - Introduction     A JavaScript library for building user interfaces. React 在 MVC 分類上屬於 View,也就是主要用來開發前端。比起直接使用 npx create-react-app,我這裡想紀錄一些較簡單且原始的 React Sample Code。 原本既有的程式碼 <!-- Some HT… Read More
  • 重新踏入網頁開發 (6) - Express - 5  Express - sendFile()     用 sendFile 把寫好的 HTML 傳出去,然後準備開始前端的開發。 import express from 'express' import path from 'path'; // 建立 express 這 module var app = express() const port = 8888 cons… Read More
  • 重新踏入網頁開發 (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… Read More
  • 重新踏入網頁開發 (5) - Blocking & Non-Blocking Blocking & Non-Blocking     Nodejs 為事件觸發的單一執行緒,不像 Apache + PHP 會自動開一個 Thread 去接每一個 Request。     Blocking Code 示範 (程式碼另有 index.js 請參照重新踏入網頁開發 (4) - Dependency injection) route.js function start_… Read More
  • 重新踏入網頁開發 (6) - Express - 3  Express - Middleware     Middleware 是會處理 req, res, next 三個物件並在 routing 時執行之 function,基本上就是 routing 時會處理的 callback function。是 Express 中蠻重要的概念。但用例子來理解比較容易。 import express from 'express' // 建立 express 這… Read More

0 意見:

張貼留言

Popular Posts