65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Express 和 MongoDB 开发 RESTful API 的 8 个步骤

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2017年2月19日

CPOL

2分钟阅读

viewsIcon

7877

在本 MEAN 栈教程中,我们将使用 Express.js 和 MongoDB 开发一个 RESTful API。

在本 MEAN 栈教程中,我们将使用 Express.js 和 MongoDB 开发一个 RESTful API。我们将遵循循序渐进的方法,以便读者更容易地开发他们的第一个 RESTful API,使用 MEAN 栈

构建 API 的步骤如下:

步骤 1:初始化项目

  • 创建一个名为 todoapp 的文件夹。
  • 在项目文件夹中打开命令提示符窗口。
  • 运行以下命令
    npm init
    此命令将创建一个包含以下详细信息的 package.json 文件

    MEAN Stack Tutorial

步骤 2:安装 Express

  • 使用以下命令安装 express
    npm install express --save

步骤 3:安装 Express 生成器

  • 使用以下命令安装 express-generator
    npm install express-generator --save

步骤 4:创建项目

  • 使用以下命令创建 express 项目
    express todoapp

    这将产生以下输出:

    create : todoapp
       create : todoapp/package.json
       create : todoapp/app.js
       create : todoapp/public
       create : todoapp/routes
       create : todoapp/routes/index.js
       create : todoapp/routes/users.js
       create : todoapp/views
       create : todoapp/views/index.jade
       create : todoapp/views/layout.jade
       create : todoapp/views/error.jade
       create : todoapp/public/stylesheets
       create : todoapp/public/stylesheets/style.css
       create : todoapp/public/javascripts
       create : todoapp/public/images
       create : todoapp/bin
       create : todoapp/bin/www
     
       install dependencies:
         $ cd todoapp && npm install
     
       run the app:
         $ DEBUG=todoapp ./bin/www

步骤 5:安装依赖项

  • package.json 文件将如下所示
    {
      "name": "todoapp",
      "version": "0.0.0",
      "private": true,
      "scripts": {
        "start": "node ./bin/www"
      },
      "dependencies": {
        "body-parser": "~1.16.0",
        "cookie-parser": "~1.4.3",
        "debug": "~2.6.0",
        "express": "~4.14.1",
        "jade": "~1.11.0",
        "morgan": "~1.7.0",
        "serve-favicon": "~2.3.2"
      }
    }
  • 使用以下命令安装所有依赖项
    npm install

注意:您可以在 MEAN 栈上找到更多有用的详细信息,特别是 AngularJS 1.x & AngularJS 2 在这里。

步骤 6:安装 HBS, MONGO

  • 使用以下命令安装 mongo 
    npm install --save mongo
    npm install --save mongodb
    npm install --save monk

步骤 7:运行 Mongo

  • 运行 mongod.exe,它将启动 MongoDB。

    Run MongoDB

  • 使用以下命令连接到 todoapp 数据库

    Mongo Exe

步骤 8:创建 Mongo 服务并连接到数据库

  • app.js 文件中,添加 mongo 数据库如下
    var mongo = require('mongodb');
    var monk = require('monk');
    var db = monk('localhost:27017/todoapp');
  • 创建一个中间件来连接到数据库
    app.use(function(req,res,next){
        req.db = db;
        next();
    });
  • 在 'routes/todo.js' 文件中创建一个新的 todo 路由
    var express = require('express');
    var router = express.Router();
    
    /* GET todos listing. */
    router.get('/', function(req, res) {
    
        res.send('Show todo list with delete and update feature (RUD)');
    });
    
    /* render NEW To-do form page. todos/new is a route path*/
    
    router.get('/new', function(req, res) {
        res.render('new_todo',{title:'Add new To-Do'});
    });
    
    module.exports = router;
  • app.js 中,添加路由进行初始化
    var todos = require('./routes/todos');
    app.use('/todos', todos);
  • views 文件夹中创建一个名为 'new_todo.jed' 的新表单模板
    extends layout
    
    block content
        h1= title
        form(name="new_todo", method="post", action="/todos/add_todo")
            div.input
                span.label Title
                input(type="text", name="title")
        div.input
            span.label Due Date
            input(type="text", name="dueDate")
            div.input
                span.label Description
                textarea(name="description", cols="40", rows="5")
            div.actions
                input(type="submit", value="add")
  • 使用以下命令运行应用程序
    npm start
  • 从浏览器中,如果我们运行 https://:3000/todos/new,我们可以看到 New todo 页面如下

    ExpressJS Tutorial

  • 下一步是编写在 routes/todos.js 文件中提交 add-todo 表单后将执行的方法。添加以下路由方法
    /* Add To-do to database*/
    router.post('/add-todo', function(req, res) {
        // Get the only one db instance in our app
        var db = req.db;
        // Get POST values, It's easy
        var title = req.body.title;
        var dueDate = req.body.dueDate;
        console.log('POST VALUES: ' + title + ' ' + dueDate);
    
       // Fetch from 'users' collection
        var todoCollection = db.get("todos");
        todoCollection.insert({
            'title' : title,
            'dueDate' : dueDate
        }, function(err, doc) {
            if(err) res.send('Problem occured when inserting in todo collection');
            else {
                console.log("Inserted");
                res.location('todos');
                res.redirect('/todos');
            }
        });
    });
  • 现在提交表单将重定向到 /todos/add-todo 路由并发出 POST 请求。todo 将保存在数据库中。

希望本 MEAN 栈教程能作为您使用 ExpressJS 和 MongoDB 的第一个 RESTful API。我们很快会推出关于相关技术的更详细的技术教程。保持联系 :-)

热门相关技术文章

文章 使用 Express 和 MongoDB 开发 RESTful API 的 8 个步骤 最先发表在 Web Development Tutorial 上。

© . All rights reserved.