ExpressJS RESTFul API


始终需要API来创建移动应用程序,单页面应用程序,使用AJAX调用并向客户端提供数据。如何构造和命名这些API和端点的流行架构风格称为 REST(Representational Transfer State)HTTP 1.1 的设计考虑了REST原则。REST由 Roy Fielding 在2000年的Paper Fielding Dissertations中引入。

RESTful URI和方法为我们提供了处理请求所需的几乎所有信息。下面给出的表总结了如何使用各种动词以及如何命名URI。我们将在最后创建一个电影API; 现在让我们讨论一下它的结构。

Method URI Details Function
GET /movies Safe, cachable 获取所有电影及其详细信息的列表
GET /movies/1234 Safe, cachable 获取Movie id 1234的详细信息
POST /movies N/A 使用提供的详细信息创建新电影。Response包含此新创建资源的URI。
PUT /movies/1234 Idempotent 修改影片ID 1234(如果尚不存在,则创建一个)。Response包含此新创建资源的URI。
DELETE /movies/1234 Idempotent 应删除电影ID 1234(如果存在)。响应应包含请求的状态。
DELETE or PUT /movies Invalid 应该是无效的。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文件。我们没有使用数据库来存储电影,而是将它们存储在内存中; 所以每次服务器重启时,我们添加的电影都会消失。这可以使用数据库或文件(使用节点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}

如果您访问无效路由,它将产生一个 无法GET错误 , 而如果您访问一个ID不存在的有效路由,则会产生404错误。

我们完成了GET路由,让我们现在转到 POST 路由。

POST路由

使用以下路由处理 POSTed 数据

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});
   }
});

这将创建一个新电影并将其存储在电影变量中。要检查此路由,请在终端中输入以下代码

curl -X POST --data "name = Toy%20story&year = 1995&rating = 8.5" http://localhost: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"
http://localhost:3000/movies/101

响应

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

删除路由

使用以下代码创建删除路由。

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创建更复杂的应用程序。