ExpressJS - RESTful API



建立移動應用程式、單頁應用程式、使用 AJAX 呼叫以及向客戶端提供資料時,始終需要 API。一種關於如何構建和命名這些 API 及其端點的流行架構風格稱為 **REST(具象狀態傳輸)**。**HTTP 1.1** 的設計就考慮了 REST 原則。REST 由 **Roy Fielding** 於 2000 年在其論文 Fielding Dissertations 中提出。

RESTful URI 和方法為我們提供了處理請求所需的大部分資訊。下表總結了如何使用各種動詞以及如何命名 URI。我們將在最後建立一個電影 API;現在讓我們討論一下它的結構。

方法 URI 細節 功能
GET /movies 安全,可快取 獲取所有電影及其詳細資訊的列表
GET /movies/1234 安全,可快取 獲取電影 ID 1234 的詳細資訊
POST /movies N/A 使用提供的詳細資訊建立一個新的電影。響應包含此新建立資源的 URI。
PUT /movies/1234 冪等 修改電影 ID 1234(如果不存在則建立一個)。響應包含此新建立資源的 URI。
DELETE /movies/1234 冪等 如果存在,則應刪除電影 ID 1234。響應應包含請求的狀態。
DELETE 或 PUT /movies 無效 應為無效。**DELETE** 和 **PUT** 應指定它們正在處理的資源。

現在讓我們在 Express 中建立此 API。我們將使用 JSON 作為我們的傳輸資料格式,因為它易於在 JavaScript 中使用並且具有其他優點。將您的 **index.js** 檔案替換為以下程式中的 **movies.js** 檔案。

index.js

var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();

var app = express();

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());

//Require the Router we defined in movies.js
var movies = require('./movies.js');

//Use the Router on the sub route /movies
app.use('/movies', movies);

app.listen(3000);

現在我們已經設定了應用程式,讓我們專注於建立 API。

首先設定 movies.js 檔案。我們沒有使用資料庫來儲存電影,而是將它們儲存在記憶體中;因此,每次伺服器重啟時,我們新增的電影都會消失。這可以透過使用資料庫或檔案(使用 node fs 模組)輕鬆模擬。

匯入 Express 後,建立一個路由器並使用module.exports匯出它 -

var express = require('express');
var router = express.Router();
var movies = [
   {id: 101, name: "Fight Club", year: 1999, rating: 8.1},
   {id: 102, name: "Inception", year: 2010, rating: 8.7},
   {id: 103, name: "The Dark Knight", year: 2008, rating: 9},
   {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];

//Routes will go here
module.exports = router;

GET 路由

讓我們定義獲取所有電影的 GET 路由 -

router.get('/', function(req, res){
   res.json(movies);
});

要測試這是否正常工作,請執行您的應用程式,然後開啟您的終端並輸入 -

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET 
localhost:3000/movies

將顯示以下響應 -

[{"id":101,"name":"Fight Club","year":1999,"rating":8.1},
{"id":102,"name":"Inception","year":2010,"rating":8.7},
{"id":103,"name":"The Dark Knight","year":2008,"rating":9},
{"id":104,"name":"12 Angry Men","year":1957,"rating":8.9}]

我們有一個獲取所有電影的路由。現在讓我們建立一個透過其 ID 獲取特定電影的路由。

router.get('/:id([0-9]{3,})', function(req, res){
   var currMovie = movies.filter(function(movie){
      if(movie.id == req.params.id){
         return true;
      }
   });
   if(currMovie.length == 1){
      res.json(currMovie[0])
   } else {
      res.status(404);//Set status to 404 as movie was not found
      res.json({message: "Not Found"});
   }
});

這將根據我們提供的 ID 獲取電影。要檢查輸出,請在您的終端中使用以下命令 -

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET 
localhost:3000/movies/101

您將獲得以下響應 -

{"id":101,"name":"Fight Club","year":1999,"rating":8.1}

如果您訪問無效路由,它將產生一個 **無法獲取錯誤**,而如果您訪問具有不存在 ID 的有效路由,它將產生一個 404 錯誤。

我們完成了 GET 路由,現在讓我們繼續 **POST** 路由。

POST 路由

使用以下路由處理 **POST** 的資料 -

router.post('/', function(req, res){
   //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){
      
      res.status(400);
      res.json({message: "Bad Request"});
   } else {
      var newId = movies[movies.length-1].id+1;
      movies.push({
         id: newId,
         name: req.body.name,
         year: req.body.year,
         rating: req.body.rating
      });
      res.json({message: "New movie created.", location: "/movies/" + newId});
   }
});

這將建立一個新的電影並將其儲存在 movies 變數中。要檢查此路由,請在您的終端中輸入以下程式碼 -

curl -X POST --data "name = Toy%20story&year = 1995&rating = 8.5" https://:3000/movies

將顯示以下響應 -

{"message":"New movie created.","location":"/movies/105"}

要測試這是否已新增到 movies 物件中,請再次執行 ** /movies/105** 的 get 請求。將顯示以下響應 -

{"id":105,"name":"Toy story","year":"1995","rating":"8.5"}

讓我們繼續建立 PUT 和 DELETE 路由。

PUT 路由

PUT 路由與 POST 路由幾乎相同。我們將為要更新/建立的物件指定 ID。以以下方式建立路由。

router.put('/:id', function(req, res){
   //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g) ||
      !req.params.id.toString().match(/^[0-9]{3,}$/g)){
      
      res.status(400);
      res.json({message: "Bad Request"});
   } else {
      //Gets us the index of movie with given id.
      var updateIndex = movies.map(function(movie){
         return movie.id;
      }).indexOf(parseInt(req.params.id));
      
      if(updateIndex === -1){
         //Movie not found, create new
         movies.push({
            id: req.params.id,
            name: req.body.name,
            year: req.body.year,
            rating: req.body.rating
         });
         res.json({message: "New movie created.", location: "/movies/" + req.params.id});
      } else {
         //Update existing movie
         movies[updateIndex] = {
            id: req.params.id,
            name: req.body.name,
            year: req.body.year,
            rating: req.body.rating
         };
         res.json({message: "Movie id " + req.params.id + " updated.", 
            location: "/movies/" + req.params.id});
      }
   }
});

此路由將執行上表中指定的功能。如果物件存在,它將使用新詳細資訊更新物件。如果不存在,它將建立一個新物件。要檢查路由,請使用以下 curl 命令。這將更新現有的電影。要建立新的電影,只需將 ID 更改為不存在的 ID。

curl -X PUT --data "name = Toy%20story&year = 1995&rating = 8.5" 
https://:3000/movies/101

響應

{"message":"Movie id 101 updated.","location":"/movies/101"}

DELETE 路由

使用以下程式碼建立一個刪除路由。-

router.delete('/:id', function(req, res){
   var removeIndex = movies.map(function(movie){
      return movie.id;
   }).indexOf(req.params.id); //Gets us the index of movie with given id.
   
   if(removeIndex === -1){
      res.json({message: "Not found"});
   } else {
      movies.splice(removeIndex, 1);
      res.send({message: "Movie id " + req.params.id + " removed."});
   }
});

以與我們檢查其他路由相同的方式檢查路由。成功刪除(例如 ID 105)後,您將獲得以下輸出 -

{message: "Movie id 105 removed."}

最後,我們的 **movies.js** 檔案將如下所示。

var express = require('express');
var router = express.Router();
var movies = [
   {id: 101, name: "Fight Club", year: 1999, rating: 8.1},
   {id: 102, name: "Inception", year: 2010, rating: 8.7},
   {id: 103, name: "The Dark Knight", year: 2008, rating: 9},
   {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];
router.get('/:id([0-9]{3,})', function(req, res){
   var currMovie = movies.filter(function(movie){
      if(movie.id == req.params.id){
         return true;
      }
   });
   
   if(currMovie.length == 1){
      res.json(currMovie[0])
   } else {
      res.status(404);  //Set status to 404 as movie was not found
      res.json({message: "Not Found"});
   }
});
router.post('/', function(req, res){
   //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){
      res.status(400);
      res.json({message: "Bad Request"});
   } else {
      var newId = movies[movies.length-1].id+1;
      movies.push({
         id: newId,
         name: req.body.name,
         year: req.body.year,
         rating: req.body.rating
      });
      res.json({message: "New movie created.", location: "/movies/" + newId});
   }
});

router.put('/:id', function(req, res) {
   //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g) ||
      !req.params.id.toString().match(/^[0-9]{3,}$/g)){
      res.status(400);
      res.json({message: "Bad Request"});
   } else {
      //Gets us the index of movie with given id.
      var updateIndex = movies.map(function(movie){
         return movie.id;
      }).indexOf(parseInt(req.params.id));
      
      if(updateIndex === -1){
         //Movie not found, create new
         movies.push({
            id: req.params.id,
            name: req.body.name,
            year: req.body.year,
            rating: req.body.rating
         });
         res.json({
            message: "New movie created.", location: "/movies/" + req.params.id});
      } else {
         //Update existing movie
         movies[updateIndex] = {
            id: req.params.id,
            name: req.body.name,
            year: req.body.year,
            rating: req.body.rating
         };
         res.json({message: "Movie id " + req.params.id + " updated.",
            location: "/movies/" + req.params.id});
      }
   }
});

router.delete('/:id', function(req, res){
   var removeIndex = movies.map(function(movie){
      return movie.id;
   }).indexOf(req.params.id); //Gets us the index of movie with given id.
   
   if(removeIndex === -1){
      res.json({message: "Not found"});
   } else {
      movies.splice(removeIndex, 1);
      res.send({message: "Movie id " + req.params.id + " removed."});
   }
});
module.exports = router;

這完成了我們的 REST API。現在您可以使用這種簡單的架構風格和 Express 建立更復雜的應用程式。

廣告