使用Express框架,更精簡的搭建網站
前一個範例算是土法煉鋼的做法,但是如果常常在架設網站,會發現那樣子始終是太累了,所以有人把常用的功能整合的更精簡,於是 express 誕生了,用express架設網站,程式碼就變很精簡了。
var express = require('express');
var app = express();
app.get('/', function (req, res) {
    res.send('Hello World');
});
app.listen(3000, function () {
    console.log('Express伺服器成功運行在localhost:3000上了');
});
你知道RESTful API嗎?
一張圖讓你搞懂Restful API

如何設計Restful API,請參考以下教學
實際使用Express實踐RESTful API
手動建立server.js檔與views資料夾,並在views資料夾中建立index.html
資料夾的意義
- views: 存放網頁檔案﹐其實就是html檔
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// 解析application/json
app.use(bodyParser.json());
// 解析application/x-www-form-urlencoded,從網頁表單送來的資料
app.use(bodyParser.urlencoded({extended: true}));
// 將含有靜態資產的目錄名稱傳遞給 express.static 中介軟體函數,就能直接開始提供檔案
app.use(express.static('public'));
app.get('/', function (req, res) {
    res.sendFile(__dirname + "/views/index.html");
});
/*
 *
 * 這邊寫上 GET POST PUT DELETE 的程式碼,請參考下面的資料
 *
 */
app.listen(3000, function () {
    console.log('Express server started.');
});
- __dirname是專案所在資料夾的路徑
- 解釋程式碼的意思
GET /users 取得所有使用者資料
app.get('/users', function (req, res) {
    var limit = req.query.limit;
    var offset = req.query.offset;
    var condiction = "";
    condiction += limit ? (" limit=" + limit) : "";
    condiction += offset ? (" offset=" + offset) : "";
    res.send("get all users." + condiction);
});
GET /users/:id 取得單個使用者資料
app.get('/users/:id', function (req, res) {
    res.send("get user. id=" + req.params.id);
});
POST /users 新增使用者資料
app.post('/users', function (req, res) {
    console.log("add user's data");
    console.log(req.body); //不用bodyParser的話就無法解析req.body
    res.send("add user. return a new user's id");
});
PUT /users/:id 更新使用者資料
app.put('/users/:id', function (req, res) {
    console.log("update user's data");
    console.log(req.body);
    res.send("update user. id=" + req.params.id);
});
DELETE /users/:id 刪除使用者資料
app.delete('/users/:id', function (req, res) {
    res.send("delete user. id=" + req.params.id);
});
怎樣將參數傳給server,有以下三種方法
- req.params:- app.get('/users/:id', ...中的- :id可以透過- req.params.id取得,- http://localhost:3000/users/123的- req.params.id就是123
 
- req.query- http://localhost:3000/user?limit=5&offset=10中的- req.query.limit等於5,- req.query.limit則是10
 
- req.body- 會打包成一包json,放在ajax的data欄位中送出,server端就能用req.body取得json資料
 
使用Ajax取用自己寫的Restful API
$.ajax({
    type: "GET",
    url: "/users",
    dataType: "json",
    success: function (response) {
        console.log(response);
    }
});
$.ajax({
    type: "POST",
    url: "/users",
    data: { "name":"doraemon", "age":12 },
    dataType: "json",
    success: function (response) {
        console.log(response);
    }
});
Nodejs 參考資料