使用Node和Express 4构建RESTful API

With the release of Express 4.0 just a few days ago, lots of our Node apps will have some changes in how they handle routing. With the changes in the Express Router, we have more flexibility in how we can define the routes for our applications.

随着几天前Express 4.0的发布,我们许多Node应用程序将在处理路由的方式上有所变化。 随着Express Router的变化,我们在为应用程序定义路由方面有了更大的灵活性。

Today we'll be looking at creating a RESTful API using Node, Express 4 and its Router, and Mongoose to interact with a MongoDB instance. We will also be testing our API using Postman in Chrome.

今天,我们将研究使用Node, Express 4及其Router和Mongoose创建RESTful API来与MongoDB实例进行交互。 我们还将在Chrome中使用Postman测试我们的API。

Let's look at the API we want to build and what it can do.

让我们看一下我们要构建的API以及它可以做什么。

我们的应用 ( Our Application )

We are going to build an API that will:

我们将构建一个API,该API将:

  • Handle CRUD for an item (we're going to use bears)

    处理物品的CRUD(我们将使用熊)
  • Have a standard URL (http://example.com/api/bears and http://example.com/api/bears/:bear_id)

    具有标准网址( http://example.com/api/bearshttp://example.com/api/bears/:bear_id
  • Use the proper HTTP verbs to make it RESTful (GET, POST, PUT, and DELETE)

    使用适当的HTTP动词使其成为RESTful( GETPOSTPUTDELETE
  • Return JSON data

    返回JSON数据
  • Log all requests to the console

    将所有请求记录到控制台

All of this is pretty standard for RESTful APIs. Feel free to switch out bears for anything that you will want to build for your application (users, superheroes, beers, etc).

所有这些都是RESTful API的相当标准。 您可以随意为应用程序要构建的任何内容(用户,超级英雄,啤酒等)关闭熊。

Make sure you have Node installed and let's get to it!

确保您已安装Node ,然后开始吧!

入门 ( Getting Started )

Let's look at all the files we will need to create our API. We will need to define our Node packages, start our server using Express, define our model, declare our routes using Express, and last but not least, test our API.

让我们看一下创建API所需的所有文件。 我们将需要定义Node包使用Express启动服务器定义模型使用Express声明路由 ,最后但并非最不重要的是测试API

Here is our file structure. We won't need many files and we'll keep this very simple for demonstration purposes. When moving to a production or larger application, you'll want to separate things out into a good structure (like having your routes in their own file).

这是我们的文件结构。 我们不需要很多文件,并且为了演示起见,我们将使其非常简单。 当转移到生产或更大的应用程序时,您需要将事物分离成一个良好的结构(例如,将路由保存在自己的文件中)。

- app/
    ----- models/
    ---------- bear.js  // our bear model
    - node_modules/     // created by npm. holds our dependencies/packages
    - package.json      // define all our node app and dependencies
    - server.js         // configure our application and create routes

定义我们的Node Packages package.json ( Defining our Node Packages package.json )

As with all of our Node projects, we will define the packages we need in package.json. Go ahead and create that file with these packages.

与所有Node项目一样,我们将在package.json定义所需的package.json 。 继续使用这些软件包创建该文件。

// package.json

{
    "name": "node-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "mongoose": "~3.6.13",
        "body-parser": "~1.0.1"
    }
}

What do these packages do? express is the Node framework. mongoose is the ORM we will use to communicate with our MongoDB database. body-parser will let us pull POST content from our HTTP request so that we can do things like create a bear.

这些软件包做什么? express是Node框架。 mongoose是我们将用于与MongoDB数据库通信的ORM。 body-parser可以让我们从HTTP请求中提取POST内容,以便我们可以进行创建熊之类的事情。

安装我们的节点包 ( Installing Our Node Packages )

This might be the easiest step. Go into the command line in the root of your application and type:

这可能是最简单的步骤。 进入应用程序根目录中的命令行,然后输入:

$ npm install

npm will now pull in all the packages defined into a node_modules folder in our project.

现在,npm将把定义的所有软件包都放入我们项目中的node_modules文件夹中。

npm is Node's package manager that will bring in all the packages we defined in package.json. Simple and easy. Now that we have our packages, let's go ahead and use them when we set up our API.

npm是Node的软件包管理器,它将引入我们在package.json定义的所有软件包。 简单容易。 现在我们有了程序包,让我们继续并在设置API时使用它们。

We'll be looking to our server.js file to setup our app since that's the main file we declared in package.json.

我们将寻找server.js文件来设置应用程序,因为那是我们在package.json声明的main文件。

设置我们的服务器server.js ( Setting Up Our Server server.js )

Node will look here when starting the application so that it will know how we want to configure our application and API.

启动应用程序时,Node将在此处查看,以便它将知道我们如何配置我们的应用程序和API。

We will start with the bear (get it?) essentials necessary to start up our application. We'll keep this code clean and commented well so we understand exactly what's going on every step of the way.

我们将从启动应用程序所必需的承担(懂吗?)要点开始。 我们将使这段代码保持干净和注释良好,以便我们准确了解此过程中每个步骤的内容。

// server.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

Wow we did a lot there! It's all very simple though so let's walk through it a bit.

哇,我们在那里做了很多! 一切都非常简单,因此让我们逐步了解一下。

Base Setup In our base setup, we pull in all the packages we pulled in using npm. We'll grab express, define our app, get bodyParser and configure our app to use it. We can also set the port for our application.

基本设置在基本设置中,我们使用npm提取所有引入的软件包。 我们将获取express,定义我们的应用,获取bodyParser并配置我们的应用以使用它。 我们还可以为我们的应用程序设置端口。

Routes for Our API This section will hold all of our routes. The structure for using the Express Router let's us pull in an instance of the router. We can then define routes and then apply those routes to a root URL (in this case, API).

API的路线本节将介绍我们的所有路线。 使用Express Router的结构让我们引入路由器的实例。 然后,我们可以定义路由 ,然后将这些路由应用于根URL(在本例中为API)。

Start our Server We'll have our express app listen to the port we defined earlier. Then our application will be live and we can test it!

启动我们的服务器我们将让Express应用程序监听我们之前定义的端口。 然后我们的应用程序将开始运行,我们可以对其进行测试!

启动我们的服务器并进行测试 ( Starting Our Server and Testing )

Let's make sure that everything is working up to this point. We will start our Node app and then send a request to the one route we defined to make sure we get a response.

让我们确保一切工作到此为止。 我们将启动Node应用程序,然后将请求发送到我们定义的一条路由,以确保获得响应。

Let's start our server. From the command line, type:

让我们启动服务器。 在命令行中,输入:

$ node server.js

You should see your Node app start up and Express will create a server.

您应该看到Node应用程序已启动,并且Express将创建服务器。

node-api-start-server

Now that we know our application is up and running, let's test it.

现在我们知道我们的应用程序已启动并正在运行,让我们对其进行测试。

使用Postman测试我们的API ( Testing Our API Using Postman )

Postman will help us test our API. It will basically send HTTP requests to a URL of our choosing. We can even pass in parameters (which we will soon) and authentication (which we won't need for this tutorial).

邮递员将帮助我们测试API。 它将基本上将HTTP请求发送到我们选择的URL。 我们甚至可以传递参数(我们将很快提供)和身份验证(本教程将不需要它们)。

Open up Postman and let's walk through how to use it.

打开Postman,让我们逐步介绍如何使用它。

postman-rest-client-node-api

All you have to do is enter your request URL, select an HTTP verb, and click Send. Simple enough right?

您所要做的就是输入请求URL选择一个HTTP动词 ,然后单击“ 发送” 。 很简单吧?

Here's the moment we've been waiting for. Does our application work the way we configured it? Enter http://localhost:8080/api into the URL. GET is what we want since we just want to get data. Now click Send.

这是我们一直在等待的时刻。 我们的应用程序是否按照配置的方式工作? 在URL中输入http://localhost:8080/apiGET是我们想要的,因为我们只想获取数据。 现在,点击发送

node-api-postman-test

Sweet! We got back exactly what we wanted. Now we know we can serve information to requests. Let's wire up our database so we can start performing CRUD operations on some bears.

甜! 我们完全得到了想要的东西。 现在我们知道可以为请求提供信息了。 让我们连接数据库,以便可以开始对某些熊执行CRUD操作。

数据库和熊模型 ( Database and Bear Model )

We'll keep this short and sweet so that we can get to the fun part of building the API routes. All we need to do is create a MongoDB database and have our application connect to it. We will also need to create a bear mongoose model so we can use mongoose to interact with our database.

我们将使它简短而有趣,以便我们可以开始构建API路由的有趣部分。 我们需要做的就是创建一个MongoDB数据库,并将我们的应用程序连接到该数据库。 我们还需要创建一个熊猫鼬模型,以便可以使用猫鼬与我们的数据库进行交互。

创建我们的数据库并连接 ( Creating Our Database and Connecting )

We will be using a database provided by Modulus. You can definitely create your own database and use it locally or use the awesome Mongolab. All you really need is a URI like below so that your application can connect.

我们将使用Modulus提供的数据库。 您绝对可以创建自己的数据库并在本地使用它,也可以使用很棒的Mongolab 。 您真正需要的只是一个如下所示的URI,以便您的应用程序可以连接。

Once you have your database created and have the URI to connect to, let's add it to our application. In server.js in the Base Setup section, let's add these two lines.

创建数据库并连接URI之后,让我们将其添加到我们的应用程序中。 在server.js的“基本设置”部分中,让我们添加这两行。

// server.js

// BASE SETUP
// =============================================================================

...

var mongoose   = require('mongoose');
mongoose.connect('mongodb://node:node@novus.modulusmongo.net:27017/Iganiq8o'); // connect to our database

...

That will grab the mongoose package and connect to our remote database hosted by Modulus. Now that we are connected to our database, let's create a mongoose model to handle our bears.

这将获取猫鼬包并连接到Modulus托管的我们的远程数据库。 现在我们已经连接到数据库,让我们创建一个猫鼬模型来处理我们的熊。

熊模型app / models / bear.js ( Bear Model app/models/bear.js )

Since the model won't be the focus of this tutorial, we'll just create a model and provide our bears with a name field. That's it. Let's create that file and define the model.

由于模型不是本教程的重点,因此我们将创建一个模型并为熊提供一个name字段。 而已。 让我们创建该文件并定义模型。

// app/models/bear.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var BearSchema   = new Schema({
    name: String
});

module.exports = mongoose.model('Bear', BearSchema);

With that file created, let's pull it into our server.js so that we can use it within our application. We'll add one more line to that file.

创建该文件后,让我们将其拉入server.js以便可以在应用程序中使用它。 我们将在该文件中再添加一行。

// server.js

// BASE SETUP
// =============================================================================

...

var Bear     = require('./app/models/bear');

...

Now our entire application is ready and wired up so we can start building out our routes. These routes will define our API and the main reason why this tutorial exists. Moving on!

现在我们的整个应用程序已准备就绪并已连接好,因此我们可以开始构建路由。 这些路线将定义我们的API以及本教程存在的主要原因。 继续!

快速路由器和路由 ( Express Router and Routes )

We will use an instance of the Express Router to handle all of our routes. Here is an overview of the routes we will require, what they will do, and the HTTP Verb used to access it.

我们将使用Express Router的实例来处理所有路由。 这是我们将需要的路由,它们将要执行的操作以及用于访问它的HTTP Verb的概述。

Route HTTP Verb Description
/api/bears GET Get all the bears.
/api/bears POST Create a bear.
/api/bears/:bear_id GET Get a single bear.
/api/bears/:bear_id PUT Update a bear with new info.
/api/bears/:bear_id DELETE Delete a bear.
路线 HTTP动词 描述
/ api / bears GET 得到所有的熊。
/ api / bears POST 制造一只熊。
/ api / bears /:bear_id GET 一只熊。
/ api / bears /:bear_id PUT 使用新信息更新熊。
/ api / bears /:bear_id DELETE 删除熊。

This will cover the basic routes needed for an API. This also keeps to a good format where we have kept the actions we need to execute (GET, POST, PUT, and DELETE) as HTTP verbs.

这将涵盖API所需的基本路由。 这也保持了良好的格式,其中我们将需要执行的动作(GET,POST,PUT和DELETE)保留为HTTP动词。

路由中间件 ( Route Middleware )

We've already defined our first route and seen it in action. The Express Router gives us a great deal of flexibility in definining our routes.

我们已经定义了第一个路线,并已将其付诸实践。 Express Router为我们提供了很大的灵活性来定义路线。

Let's say that we wanted something to happen every time a request was sent to our API. For this example we are just going to console.log() a message. Let's add that middleware now.

假设每次发送请求到API时 ,我们都希望发生一些事情 。 对于此示例,我们仅向console.log()发送一条消息。 现在添加该中间件。

// server.js

...

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

All we needed to do to declare that middleware was to use router.use(function()). The order of how we define the parts of our router is very important. They will run in the order that they are listed and thanks to the changes in Express 4.0, we won't have problems doing this like in Express 3.0. Everything will run in the correct order.

我们要做的就是声明中间件是使用router.use(function()) 。 我们定义路由器各部分的顺序非常重要。 它们将按照列出的顺序运行,并且由于Express 4.0中更改 ,我们不会像Express 3.0那样遇到问题。 一切都会以正确的顺序运行。

We are sending back information as JSON data. This is standard for an API and will help the people using our API to use our data.

我们正在将信息作为JSON数据发送回去。 这是API的标准,将帮助使用我们的API的人们使用我们的数据。

We will also add next() to indicate to our application that it should continue to the other routes. This is important because our application would stop at this middleware without it.

我们还将添加next()来向我们的应用程序表明它应该继续其他路线。 这很重要,因为没有它,我们的应用程序将在此中间件处停止。

Middleware Uses Using middleware like this can be very powerful. We can do validations to make sure that everything coming from a request is safe and sound. We can throw errors here in case something is wrong. We can do some extra logging for analytics or any statistics we'd like to keep. There are many possibilities here. Go wild.

中间件的用途使用这样的中间件可能非常强大。 我们可以进行验证,以确保来自请求的所有内容都是安全无害的。 如果出现问题,我们可以在此处抛出错误。 我们可以做一些额外的日志记录,以进行分析或我们希望保留的任何统计信息。 这里有很多可能性。 去野外。

测试我们的中间件 ( Testing Our Middleware )

Now when we send a request to our application using Postman, Something is happening will be logged to our Node console (the command line).

现在,当我们使用Postman向应用程序发送请求时, Something is happening将被记录到我们的Node控制台(命令行)中。

node-api-route-middleware-express

With middleware, we can do awesome things to requests coming into our API. We will probably want to make sure that the user is authenticated to access our API. We'll go over that in a future article, but for now let's just log something to the console with our middleware.

借助中间件,我们可以对进入我们的API的请求进行出色的处理。 我们可能要确保用户通过身份验证才能访问我们的API。 我们将在以后的文章中讨论这一点,但现在,让我们仅使用中间件将某些内容记录到控制台中。

创建基本路线 ( Creating the Basic Routes )

We will now create the routes to handle getting all the bears and creating a bear. This will both be handled using the /api/bears route. We'll look at creating a bear first so that we have bears to work with.

现在,我们将创建处理所有熊创建熊的路线。 两者都将使用/api/bears路由进行处理。 我们将首先考虑创建熊,以便我们可以使用熊。

创建Bear POST / api / bears ( Creating a Bear POST /api/bears )

We will add the new route to handle POST and then test it using Postman.

我们将添加新的路由来处理POST,然后使用Postman对其进行测试。

// server.js

...

// ROUTES FOR OUR API
// =============================================================================

... // <-- route middleware and first route are here

// more routes for our API will happen here

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')

    // create a bear (accessed at POST http://localhost:8080/api/bears)
    .post(function(req, res) {

        var bear = new Bear();      // create a new instance of the Bear model
        bear.name = req.body.name;  // set the bears name (comes from the request)

        // save the bear and check for errors
        bear.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Bear created!' });
        });

    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

Now we have created the POST route for our application. We will use Express's router.route() to handle multiple routes for the same URI. We are able to handle all the requests that end in /bears.

现在,我们为应用程序创建了POST路由。 我们将使用Express的router.route()处理同一URI的多个路由。 我们能够处理所有以/bears结尾的请求。

Let's look at Postman now to create our bear.

现在让我们看一下邮递员来创建我们的熊。

node-api-postman-post-create-bear

Notice that we are sending the name data as x-www-form-urlencoded. This will send all of our data to the Node server as query strings.

请注意,我们将name数据发送为x-www-form-urlencoded 。 这会将所有数据作为查询字符串发送到Node服务器。

We get back a successful message that our bear has been created. Let's handle the API route to get all the bears so that we can see the bear that just came into existence.

我们收到一条成功的消息,说我们已经创建了熊。 让我们处理一下API路线以获取所有熊,以便我们可以看到刚诞生的熊。

获取所有熊GET / api / bears ( Getting All Bears GET /api/bears )

This will be a simple route that we will add onto the router.route() we created for the POST. With router.route(), we are able to chain together the different routes. This keeps our application clean and organized.

这是一条简单的路由,我们将其添加到为POST创建的router.route() 。 使用router.route(),我们可以将不同的路由链接在一起。 这样可以使我们的应用程序保持整洁有序。

// server.js

...

// ROUTES FOR OUR API
// =============================================================================

... // <-- route middleware and first route are here

// more routes for our API will happen here

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')

    // create a bear (accessed at POST http://localhost:8080/api/bears)
    .post(function(req, res) {

        ...

    })

    // get all the bears (accessed at GET http://localhost:8080/api/bears)
    .get(function(req, res) {
        Bear.find(function(err, bears) {
            if (err)
                res.send(err);

            res.json(bears);
        });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

Straightforward route. Just send a GET request to http://localhost:8080/api/bears and we'll get all the bears back in JSON format.

直截了当的路线。 只需将GET请求发送到http://localhost:8080/api/bears ,我们就会以JSON格式返回所有熊。

node-api-postman-get-all

为单个项目创建路线 ( Creating Routes for A Single Item )

We've handled the group for routes ending in /bears. Let's now handle the routes for when we pass in a parameter like a bear's id.

我们已经处理了以/bears结尾的路由组。 现在让我们处理传递诸如熊的id之类的参数时的路线。

The things we'll want to do for this route, which will end in /bears/:bear_id will be:

我们将为此路由做的事情将以/bears/:bear_id结尾,它是:

  • Get a single bear.

    一只熊。
  • Update a bear's info.

    更新熊的信息。
  • Delete a bear.

    删除熊。

The :bear_id from the request will be accessed thanks to that body-parser package we called earlier.

由于之前调用了body-parser包,因此可以访问请求中的:bear_id

获取单个Bear GET / api / bears /:bear_id ( Getting a Single Bear GET /api/bears/:bear_id )

We'll add another router.route() to handle all requests that have a :bear_id attached to them.

我们将添加另一个router.route()来处理所有附加了:bear_id请求。

// server.js

...

// ROUTES FOR OUR API
// =============================================================================

...

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
    ...

// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')

    // get the bear with that id (accessed at GET http://localhost:8080/api/bears/:bear_id)
    .get(function(req, res) {
        Bear.findById(req.params.bear_id, function(err, bear) {
            if (err)
                res.send(err);
            res.json(bear);
        });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

From our call to get all the bears, we can see the long id of one of our bears. Let's grab that id and test getting that single bear in Postman.

从我们得到所有熊的呼吁中,我们可以看到我们一只熊的长号。 让我们获取该id并测试在Postman中获得那只熊。

node-api-postman-get-single

We can grab one bear from our API now! Let's look at updating that bear's name. Let's say he wants to be more sophisiticated so we'll rename him from Klaus to Sir Klaus.

我们现在可以从API中抓一只熊! 让我们看一下更新那个熊的名字。 假设他想变得更老练,所以我们将他从克劳斯改名为克劳斯爵士

更新熊的信息PUT / api / bears /:bear_id ( Updating a Bear's Info PUT /api/bears/:bear_id )

Let's chain a route onto our this router.route() and add a .put().

让我们将路由链接到此router.route()并添加.put()

// server.js

...

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
    ...

// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')

    // get the bear with that id (accessed at GET http://localhost:8080/api/bears/:bear_id)
    .get(function(req, res) {
        ...
    })

    // update the bear with this id (accessed at PUT http://localhost:8080/api/bears/:bear_id)
    .put(function(req, res) {

        // use our bear model to find the bear we want
        Bear.findById(req.params.bear_id, function(err, bear) {

            if (err)
                res.send(err);

            bear.name = req.body.name;  // update the bears info

            // save the bear
            bear.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Bear updated!' });
            });

        });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

We will use the given id from the PUT request, grab that bear, make changes, and save him back to the database.

我们将使用来自PUT请求的给定id ,抓住那只熊,进行更改,然后将其保存回数据库。

node-api-post-man-update-record

We can also use the GET /api/bears call we used earlier to see that his name has changed.

我们还可以使用我们之前使用的GET /api/bears调用来查看他的名字已更改。

node-api-postman-all-updated

删除熊DELETE / api / bears /:bear_id ( Deleting a Bear DELETE /api/bears/:bear_id )

When someone requests that a bear is deleted, all they have to do is send a DELETE to /api/bears/:bear_id

当有人要求删除熊时,他们所要做的就是将DELETE发送到/api/bears/:bear_id

Let's add the code for deleting bears.

让我们添加删除熊的代码。

// server.js

...

// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
    ...

// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')

    // get the bear with that id (accessed at GET http://localhost:8080/api/bears/:bear_id)
    .get(function(req, res) {
        ...
    })

    // update the bear with this id (accessed at PUT http://localhost:8080/api/bears/:bear_id)
    .put(function(req, res) {
        ...
    })

    // delete the bear with this id (accessed at DELETE http://localhost:8080/api/bears/:bear_id)
    .delete(function(req, res) {
        Bear.remove({
            _id: req.params.bear_id
        }, function(err, bear) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

...

Now when we send a request to our API using DELETE with the proper bear_id, we'll delete our bear from existence.

现在,当我们使用带有正确的bear_id DELETE向我们的API发送请求时,我们将从存在中删除我们的bear。

node-api-postman-delete

When we try to get all the bears, there will be nothing left of them.

当我们设法收拾所有的熊时,它们将一无所有。

node-api-postman-get-all-nothing

结论 ( Conclusion )

We now have the means to handle CRUD on a specific resource (our beloved bears) through our own API. Using the techniques above should be a good foundation to move into building larger and more robust APIs.

现在,我们可以通过自己的API处理特定资源(我们心爱的熊)上的CRUD。 使用以上技术应该成为构建更大,更强大的API的良好基础。

This has been a quick look at creating a Node API using Express 4. There are many more things you can do with your own APIs. You can add authentication, create better error messages, add different sections so you're not just working with bears.

这是使用Express 4创建Node API的快速概览。您可以使用自己的API做更多的事情。 您可以添加身份验证,创建更好的错误消息,添加不同的部分,以使您不仅可以与熊市打交道。

Sound off in the comments if you have any questions or would like to see any specific topics in the future.

如果您有任何疑问或希望以后再看到任何特定主题,请在评论中忽略。

翻译自: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值