[英]How to properly handle my routing for a REST API
Apologies if this is a newbie question .如果这是一个新手问题,请道歉。 How should I go about structuring my REST API (I use Node & Express).
我应该如何构建我的 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);
While I understand I can use the following for larger scale functions like creating recipes and deleting recipes and etc虽然我知道我可以将以下内容用于更大规模的功能,例如创建配方和删除配方等
router.get('/', (req, res, next) => {
// Get Recipes
});
router.post('/',checkAuth, (req, res, next) => {
// Create Recipe
});
router.get('/:recipeID', (req, res, next) => {
// Get Specific Recipe
});
However I am currently stuck on how to handle the inner details or specific resources.但是,我目前坚持如何处理内部细节或特定资源。 For example : Let's say I would like to add a step to the recipe.
例如:假设我想在配方中添加一个步骤。 Would this specific instance be one where I can put a verb or ?
这个特定实例是我可以放置动词的实例吗? My current idea is to:
我目前的想法是:
router.post('/:recipeID/steps',checkAuth, (req, res, next) => {
// Add Steps to recipeID if it exists
});
so to basically add urls for the properties and handle them that way since verbs are apparently a REST API sin.所以基本上为属性添加url并以这种方式处理它们,因为动词显然是REST API罪。
router.post('/:recipeID/:steps',checkAuth, (req, res, next) => {
if (req.params.steps === 'first') {//based on your requirements
} else if (condition) {
}
});
However, There are a few rest API rules for different actions.但是,对于不同的操作,有一些 rest API 规则。
GET /users
: to get user list. GET /users
: 获取用户列表。GET /users/:userid
: to get information to specific user. GET /users/:userid
:获取特定用户的信息。POST /users
: to create user. POST /users
: 创建用户。PUT /users
to update specific user information. PUT /users
更新特定用户信息。 It might help you to understand the best approach of design API endpoints.它可能会帮助您了解设计 API 端点的最佳方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.