在 Node.js 上构建 RESTful API 的 3 个技术方案:Express,Koa,Hapi

RESTful API 是现代 Web 应用程序的常见组成部分,它们提供了一种简单而有效的方式来处理客户端和服务器之间的数据传输。在 Node.js 上构建 RESTful API 的过程中,我们可以使用一些流行的框架,如 Express、Koa 和 Hapi。本文将深入探讨这三个框架的优缺点以及如何使用它们来构建 RESTful API。

Express

Express 是 Node.js 中最受欢迎的 Web 框架之一,它具有简单的 API 和灵活的路由功能。Express 可以帮助我们快速构建 RESTful API,而且它的文档和社区支持非常好,因此可以轻松找到答案和解决方案。

下面是一个使用 Express 构建 RESTful API 的示例代码:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

let books = [
  { id: 1, title: 'JavaScript: The Good Parts', author: 'Douglas Crockford' },
  { id: 2, title: 'JavaScript: The Definitive Guide', author: 'David Flanagan' },
];

app.get('/books', (req, res) => {
  res.json(books);
});

app.get('/books/:id', (req, res) => {
  const book = books.find(b => b.id === parseInt(req.params.id));
  if (!book) return res.status(404).send('The book with the given ID was not found.');
  res.json(book);
});

app.post('/books', (req, res) => {
  const book = {
    id: books.length + 1,
    title: req.body.title,
    author: req.body.author,
  };
  books.push(book);
  res.json(book);
});

app.put('/books/:id', (req, res) => {
  const book = books.find(b => b.id === parseInt(req.params.id));
  if (!book) return res.status(404).send('The book with the given ID was not found.');

  book.title = req.body.title;
  book.author = req.body.author;
  res.json(book);
});

app.delete('/books/:id', (req, res) => {
  const book = books.find(b => b.id === parseInt(req.params.id));
  if (!book) return res.status(404).send('The book with the given ID was not found.');

  const index = books.indexOf(book);
  books.splice(index, 1);
  res.json(book);
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

Koa

Koa 是 Express 的后继者,它具有更加简洁的 API 和更好的错误处理机制。Koa 的核心是中间件,它允许我们以一种非常灵活的方式来处理请求和响应。Koa 的文档相对较少,但是它的社区非常活跃,因此可以轻松找到解决方案。

下面是一个使用 Koa 构建 RESTful API 的示例代码:

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');

const app = new Koa();
app.use(bodyParser());

let books = [
  { id: 1, title: 'JavaScript: The Good Parts', author: 'Douglas Crockford' },
  { id: 2, title: 'JavaScript: The Definitive Guide', author: 'David Flanagan' },
];

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = err.message;
  }
});

app.use(async (ctx) => {
  switch (ctx.method) {
    case 'GET':
      if (ctx.url === '/books') {
        ctx.body = books;
      } else if (ctx.url.match(/^\/books\/(\d+)$/)) {
        const id = parseInt(ctx.url.match(/^\/books\/(\d+)$/)[1]);
        const book = books.find(b => b.id === id);
        if (!book) {
          ctx.throw(404, 'The book with the given ID was not found.');
        }
        ctx.body = book;
      }
      break;
    case 'POST':
      if (ctx.url === '/books') {
        const book = {
          id: books.length + 1,
          title: ctx.request.body.title,
          author: ctx.request.body.author,
        };
        books.push(book);
        ctx.body = book;
      }
      break;
    case 'PUT':
      if (ctx.url.match(/^\/books\/(\d+)$/)) {
        const id = parseInt(ctx.url.match(/^\/books\/(\d+)$/)[1]);
        const book = books.find(b => b.id === id);
        if (!book) {
          ctx.throw(404, 'The book with the given ID was not found.');
        }
        book.title = ctx.request.body.title;
        book.author = ctx.request.body.author;
        ctx.body = book;
      }
      break;
    case 'DELETE':
      if (ctx.url.match(/^\/books\/(\d+)$/)) {
        const id = parseInt(ctx.url.match(/^\/books\/(\d+)$/)[1]);
        const book = books.find(b => b.id === id);
        if (!book) {
          ctx.throw(404, 'The book with the given ID was not found.');
        }
        const index = books.indexOf(book);
        books.splice(index, 1);
        ctx.body = book;
      }
      break;
  }
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

Hapi

Hapi 是一个功能强大的 Web 框架,它提供了一些非常有用的功能,如路由、输入验证和缓存控制。Hapi 的文档非常详细,而且它的社区也非常活跃,因此可以轻松找到答案和解决方案。

下面是一个使用 Hapi 构建 RESTful API 的示例代码:

const Hapi = require('@hapi/hapi');

const init = async () => {
  const server = Hapi.server({
    port: process.env.PORT || 3000,
  });

  let books = [
    { id: 1, title: 'JavaScript: The Good Parts', author: 'Douglas Crockford' },
    { id: 2, title: 'JavaScript: The Definitive Guide', author: 'David Flanagan' },
  ];

  server.route({
    method: 'GET',
    path: '/books',
    handler: (request, h) => {
      return books;
    },
  });

  server.route({
    method: 'GET',
    path: '/books/{id}',
    handler: (request, h) => {
      const book = books.find(b => b.id === parseInt(request.params.id));
      if (!book) {
        return h.response('The book with the given ID was not found.').code(404);
      }
      return book;
    },
  });

  server.route({
    method: 'POST',
    path: '/books',
    handler: (request, h) => {
      const book = {
        id: books.length + 1,
        title: request.payload.title,
        author: request.payload.author,
      };
      books.push(book);
      return book;
    },
  });

  server.route({
    method: 'PUT',
    path: '/books/{id}',
    handler: (request, h) => {
      const book = books.find(b => b.id === parseInt(request.params.id));
      if (!book) {
        return h.response('The book with the given ID was not found.').code(404);
      }
      book.title = request.payload.title;
      book.author = request.payload.author;
      return book;
    },
  });

  server.route({
    method: 'DELETE',
    path: '/books/{id}',
    handler: (request, h) => {
      const book = books.find(b => b.id === parseInt(request.params.id));
      if (!book) {
        return h.response('The book with the given ID was not found.').code(404);
      }
      const index = books.indexOf(book);
      books.splice(index, 1);
      return book;
    },
  });

  await server.start();
  console.log(`Server running on ${server.info.uri}`);
};

init();

总结

在本文中,我们深入探讨了在 Node.js 上构建 RESTful API 的三个流行框架:Express、Koa 和 Hapi。Express 是最受欢迎的框架之一,它具有简单的 API 和灵活的路由功能。Koa 是 Express 的后继者,它具有更加简洁的 API 和更好的错误处理机制。Hapi 是一个功能强大的框架,它提供了一些非常有用的功能,如路由、输入验证和缓存控制。

无论您选择哪个框架,都需要确保您的代码易于维护和扩展,并且对性能有良好的表现。在编写代码之前,请花时间研究每个框架的文档和示例代码,这将有助于您更好地了解每个框架的优缺点并做出明智的选择。

来源:JavaScript中文网 ,转载请注明来源 本文地址:https://www.javascriptcn.com/post/65c42eeaadd4f0e0ffea1a71