簡單範例

專案架構可參考:

https://node-postgres.com/guides/async-express

使用表單post傳送資料

1.加入express

var express = require("express");
var app = express();

2.加入模板引擎Handlebars

var exphbs  = require('express-handlebars');
app.engine('hbs', exphbs());
app.set('view engine', 'hbs');

3.設定監聽port與簡單路由

app.get("/",function(req,res){

res.render('home');
});
app.post("/signup",function(req,res){
req.on("data",function(data){
    console.log(data.toString());
});
});

app.listen("3000",function(){
    console.log("listening3000");
});

根目錄下建造一個views資料夾 裡面放入home.hbs

點擊按鈕後即可看到console

使用bodyParser

不用使用on去監聽

記得導回頁面,和結束回應

延續前兩章

現在專案目錄如下

根目錄的index.js為

routes下的index.js為

public資料夾為空

使用Handlebars 當模板引擎

在根目錄的index.js加入

之後再下面再加入(記得加在var app = express();後)

再把routes中的index.html裡面的這段改為

最後創建views資料夾於根目錄,裡面放入main.handlebars

資料夾名稱必須為views,因為那是express預設的模板資料夾

重啟server即可看到畫面。

之後我們試著讓render時傳入參數

routes內的index.js改為

views內的main.handlebars改為

即可看到,產生的畫面資料變為render提供的第二個物件參數的值

使用簡單的條件判斷render

先在routes的index.js

main.handlebars

之在在把

title1的false改為true看看

使用each再render時 去遍歷陣列

測試ES6的[...]方法

發現直接執行會錯誤,所以要改為

有關Node.js目前支援的ES6方法可參考 https://nodejs.org/en/docs/es6/

render時加入function

簡單範例part2

Last updated

Was this helpful?