【问题标题】:How to properly handle my routing for a REST API如何正确处理我的 REST API 路由
【发布时间】:2019-08-10 22:16:33
【问题描述】:

抱歉,如果这是一个新手问题。我应该如何构建我的 REST API(我使用 Node 和 Express)。

const mongoose = require('mongoose');

const recipeSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {
        type: String,
        required: true
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'UserData',
        required: true
    },
    description: String,
    ingredients: [String],
    steps: [String],
    bookmarkNumber: Number,
    likeNumber: Number,
    rating: Number
})

module.exports = mongoose.model('Recipe', recipeSchema); 

虽然我知道我可以将以下内容用于更大规模的功能,例如创建食谱和删除食谱等

router.get('/', (req, res, next) => {
  // Get Recipes
});

router.post('/',checkAuth, (req, res, next) => {
  // Create Recipe
});

router.get('/:recipeID', (req, res, next) => {
// Get Specific Recipe
});

但是,我目前被困在如何处理内部细节或特定资源上。例如:假设我想在配方中添加一个步骤。这个特定的实例是我可以放置动词的实例吗?我目前的想法是:

router.post('/:recipeID/steps',checkAuth, (req, res, next) => {
  // Add Steps to recipeID if it exists
});

所以基本上为属性添加 url 并以这种方式处理它们,因为动词显然是 REST API 的罪过。

【问题讨论】:

  • 您应该查看Express 4.x API 参考。这真的很容易理解和很好的解释,在你的情况下,本节将解决你的疑惑:expressjs.com/en/4x/api.html#req
  • 首先,非常感谢您回答我的问题。我主要关心的更多是应该如何完成并遵循 Hateoas,因为我仍在尝试学习和掌握 REST API 结构。不过,我肯定会看一下 expressjs 文档。 restfulapi.net/hateoas.

标签: javascript node.js rest express api-design


【解决方案1】:
router.post('/:recipeID/:steps',checkAuth, (req, res, next) => {
   if (req.params.steps === 'first') {//based on your requirements

     } else if (condition) {

     }
});

但是,对于不同的操作,有一些其他 API 规则。

  • GET /users:获取用户列表。
  • GET /users/:userid :获取特定用户的信息。
  • POST /users:创建用户。
  • PUT /users 更新特定用户信息。

它可能会帮助您了解设计 API 端点的最佳方法。

【讨论】:

  • 首先,非常感谢您花时间回答我的问题。那么正确的做法是将属性分解成自己的特定名词,并根据需要在那里设置它们的功能?
  • 是的!如果有人告诉我做这种功能,我会按照上面的方法做。
  • 没有具体的规则/规定,它以你为基础,对你来说很容易。
  • 我已经更新了我的答案,请检查,它可能会帮助你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2019-12-31
  • 2013-12-17
  • 2014-09-15
  • 1970-01-01
  • 2017-03-07
  • 2021-09-08
相关资源
最近更新 更多