Node express 實作網站

安裝完Node之後就已經有網站功能          參考                              

建立一個node.js

// node.js 內建 http 相關 module
const http = require('http')
// createServer() 要傳入的參數是 function
const server = http.createServer(handler)

// 兩個參數分別是 request 和 response,這裡使用命名慣例寫法
function handler(req, res) {
  console.log(req.url)  // 印出 req 網址
  res.write('Hello World!')   // 指定 respone 回傳內容
  res.end()   // 結束這個 response
}

// 常見為 80 port,測試時使用 5001 port 就不易發生衝突
server.listen(5001)

我們可以加上轉址功能

const http = require('http')
const server = http.createServer(handler)

function handler(req, res) {
  console.log(req.url)  // 印出 req 網址
  if (req.url === '/hello') {
    // 參數分別是 request 的 status code 和內容格式,告訴瀏覽器如何解析網頁
    res.writeHead(200, {            // 200: 請求成功
      'Content-Type': 'text/html'
    })
    res.write('<h1>hello!</h1>')    // 也可以加上 HTML 標籤
  } else if (req.url === '/bye') {
    res.write('bye!')
  } else {
    res.write('Invalid url')
  }
  res.end()   // 結束這個 response
}

server.listen(5001)
安裝express
 npm install express --save

用express 實作一個Hello World

// 引入 library
const express = require('express');
// express 引入的是一個 function
const app = express();
// 建立一個不易產生衝突的 port 用來測試
const port = 5001;

// 如何處理不同的 request,參數分別為 url 和要執行的 function
app.get('/', (req, res) => {
  res.send('hello world!')
})

app.get('/bye', (req, res) => {
  res.send('bye!')
})

// 運行這個 port,參數分別為 port 和要執行的 function
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
MVC 基本架構
MVC(Model–view–controller):是一種應用程式架構,透過將程式碼拆成分成模型(Model)、視圖(View)和控制器(Controller)三個部分,並透過路由系統,建立整個應用程式的設計模式。

在 MVC 架構中,request 流程大致如下:
1.發出的 request 會由 Controller 來處理
2.接著 Controller 會和 Model 拿取 data
3.Controller 再把拿到的資料給 View,由 View 提供的 template
4.最後 Controller 再結合 data 和 template,回傳 respon
透過 Express 提供的 template engines 來實作 View

1.安裝ejs

npm install ejs

EJS 語法是透過<% %>符號,和 PHP 語法其實很類似,語法又可分為三種:

<% JavaScript 程式碼 %>
<%- %> 會經過解析然後印出來,用於引入 HTML 內容
<%= %> 會直接印出原始碼,用於輸出資料,避免被解析成語法,可視為一種 XSS 防禦

2.設定index.js

// 設定 view engine
app.set('view engine', 'ejs')

3.預設目錄會是 /views,因此需要新建一個資料夾 views,並在資料夾中建立一個 hello.ejs 檔

4.在 hello.ejs 檔中輸入簡單的程式碼進行測試,例如:<h1>Hello</h1>

5.接著調整 index.js 程式碼,告訴 express 去 render views 目錄底下叫做 hello 的檔案:

const express = require('express');
const app = express();
const port = 5001;

// 設定 view engine
app.set('view engine', 'ejs')

app.get('/', (req, res) => {
  res.send('index')
})

app.get('/hello', (req, res) => {
// 叫 express 去 render views 底下叫做 hello 的檔案,副檔名可省略
  res.render('hello')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料