简体   繁体   English

expressjs rest API 的好模式?

[英]Good pattern for expressjs rest APIs?

In order to organize my code I decided to create a methods folder and for each URL endpoint (website.com/billings for example) I store the endpoint name as a js file.为了组织我的代码,我决定创建一个方法文件夹,并为每个 URL 端点(例如 website.com/billings)将端点名称存储为一个 js 文件。

//expressJS configuration...
const billings = require('./methods/billings.js');

app.get('/billings', billings.get);
app.post('/billings', billings.post);

Then in methods/billings.js然后在methods/billings.js

Is there a better way?有没有更好的办法? Or a convention?还是公约?

get = async (req, res) => {
    //...
}
post = async (req, res) => {
    //...
}
module.exports.get = get;
module.exports.post = post;

There are a lot of ways you can organize your code but i think that a very good way to do so is to use express generator that creates a skeleton with a good folder structure and provides you with an idea how to organize everything properly.有很多方法可以组织代码,但我认为一个很好的方法是使用express 生成器创建一个具有良好文件夹结构的骨架,并为您提供如何正确组织所有内容的想法。 MDN has a great express tutorial that should answer a lot of your questions. MDN 有一个很棒的快速教程,可以回答你的很多问题。 Here is a github link of that tutorial were you can see how they organized code in their REST api.这是该教程的github 链接,您可以看到他们如何在 REST api 中组织代码。 I hope this helps.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM