简体   繁体   English

使用node.js创建REST API的最佳实践

[英]Best Practice to create REST APIs using node.js

I am from .Net and C# background and I am new to Node.js. 我来自.Net和C#背景,并且是Node.js的新手。 I am working on a project, which is mix of MongoDB and Node.JS. 我正在研究一个项目,该项目混合使用MongoDB和Node.JS。

In MongoDB, data from various tools is stored in different different collections. 在MongoDB中,来自各种工具的数据存储在不同的集合中。 I have to create multiple REST APIs using Node.JS for CRUD operation on that data, these APIs will be called from React.JS application. 我必须使用Node.JS对该数据进行CRUD操作来创建多个REST API,这些API将从React.JS应用程序中调用。

I want to keep APIs into separate files for seperate tool and then calling including all files into app.js file. 我想将API保留在用于单独工具的单独文件中,然后调用将所有文件都包含到app.js文件中。

Please help me with best approach. 请以最佳方式帮助我。

For POC purpose, I created a node.js application, where I created app.js file and written all my code for GET|POST|DELETE APIs. 出于POC的目的,我创建了一个node.js应用程序,在其中创建了app.js文件,并为GET | POST | DELETE API编写了所有代码。 This is working fine. 一切正常。

var _expressPackage = require("express");  
var _bodyParserPackage = require("body-parser");  
var _sqlPackage = require("mssql");  
var app = _expressPackage();  
var cors = require("cors");
var auth = require('basic-auth');
var fs = require('fs');
const nodeMailer = require('nodemailer'); 


//Lets set up our local server now.  
var server = app.listen(process.env.PORT || 4000, function () {  
    var port = server.address().port;  
    console.log("App now running on port", port);  
});  
app.get("/StudentList", function(_req ,_res){  
    console.log("Inside StudentList");
    var Sqlquery = "select * from tbl_Host where HostId='1'";    
    GetQueryToExecuteInDatabase(_req,_res, Sqlquery,function(err,data){       
        console.log(data);
    });
});

Don't know exactly what your app intends to do, but usually if you are not serving webpages and your API is not too complex, there is no need to use express. 不完全知道您的应用程序打算做什么,但是通常如果您不提供网页并且您的API不太复杂,则无需使用express。 You can build a simple server natively in NodeJS to serve data. 您可以在NodeJS中本地构建一个简单的服务器来提供数据。

Additionally, if your app has many routes (or is likely to in the future), it is a good idea to put helper functions like GetQueryToExecuteInDatabase() in a separate file outside of app.js such as utils.js. 另外,如果您的应用程序有很多路由(或将来可能会使用),则最好将诸如GetQueryToExecuteInDatabase()之类的辅助函数放在app.js之外的单独文件中,例如utils.js。

Based on what I have understood about what you want to do, your file structure should look something like this: 根据我对要执行的操作的了解,文件结构应如下所示:

  • data (db related files) 数据(db相关文件)
  • services (contains one file per api service) 服务(每个api服务包含一个文件)
  • app.js app.js
  • utils.js utils.js

Hope this helps. 希望这可以帮助。

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

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