ExpressJS RESTFul API

  • RESTFul API

    创建移动应用程序,单页应用程序,使用AJAX调用并向客户端提供数据始终需要API。关于如何构造和命名这些API和端点的一种流行的体系结构样式称为REST(代表性传输状态)。HTTP 1.1的设计考虑了REST原则。REST由Roy Fielding于2000年在他的Paper Fielding论文中介绍。RESTful URI和方法为我们提供了处理请求所需的几乎所有信息。下表列出了应如何使用各种动词以及如何命名URI。我们将在最后创建一个电影API。现在让我们讨论它的结构。
    Method URI Details Function
    get /movies 安全,可携带 获取所有电影及其详细信息的列表
    get /movies/1234 安全,可携带 获取电影ID 1234的详细信息
    post /movies 不适用 使用提供的详细信息创建新电影。响应包含此新创建资源的URI。
    put /movies/1234 等幂的 修改电影ID 1234(如果尚不存在,则创建一个)。响应包含此新创建资源的URI。
    delete /movies/1234 等幂的 电影ID 1234(如果存在)应删除。响应应包含请求的状态。
    delete或put /movies 无效 应该是无效的。DELETE和PUT应该指定它们正在处理的资源。
    现在让我们在Express中创建此API。我们将使用JSON作为传输数据格式,因为它很容易在JavaScript中使用并具有其他好处。
    
    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}
    ];
    
    //路由都定义到这里来
    module.exports = router;
    
    router.get('/', function(req, res){
        res.json(movies);
     });
    
  • GET 路由

    让我们定义获取所有电影的GET路由-
    >
    
    router.get('/', function(req, res){
       res.json(movies);
    });
    
    要测试是否可以正常运行,我们这里介绍一款HTTP请求工具POSTman,下载安装它。-
    这时候我们测试GET http://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为101的电影的示例:
  • 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变量中。要检查此路由,用设置三个参数(name,year,rating)的请求体,用POST请求URL:http://localhost:3000/movies -
  • 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});
          }
       }
    });
    
    此路由将执行上表中指定的函数。如果存在,它将使用新的详细信息更新对象。如果不存在,它将创建一个新对象。要检查路由,这将更新现有电影。要创建新的电影,只需将ID更改为不存在的ID。
    下图我们把id为101的电影进行更改
    下图我们把添加id为1001的电影
  • DELETE 路由

    使用以下代码创建DELETE路由-
    
    router.delete('/:id', function(req, res){
       var removeIndex = movies.map(function(movie){
          return movie.id;
       }).indexOf(parseInt(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."});
       }
    });
    
    DELETE请求http://localhost:3000/103 成功删除后(例如id 103),您将获得以下输出-
    最后,我们的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('/', function(req, res){
        res.json(movies);
     });
    
    // 根据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"});
        }
     });
    
    // 添加一条电影
    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 {
           // 最新的id等于最后一条记录的id+1
           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});
        }
     });
    
     // 根据id更新电影,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});
           }
        }
     });
    
     // 删除电影
     router.delete('/:id', function(req, res){
        var removeIndex = movies.map(function(movie){
           return movie.id;
        }).indexOf(parseInt(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创建更复杂的应用程序。