簡體   English   中英

如何正確處理我的 REST API 路由

[英]How to properly handle my routing for a REST API

如果這是一個新手問題,請道歉。 我應該如何構建我的 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罪。

router.post('/:recipeID/:steps',checkAuth, (req, res, next) => {
   if (req.params.steps === 'first') {//based on your requirements

     } else if (condition) {

     }
});

但是,對於不同的操作,有一些 rest API 規則。

  • GET /users : 獲取用戶列表。
  • GET /users/:userid :獲取特定用戶的信息。
  • POST /users : 創建用戶。
  • PUT /users更新特定用戶信息。

它可能會幫助您了解設計 API 端點的最佳方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM