[英]How to accept Huge amount of API requests in Node JS
I recently started learning Node JS. 我最近开始学习Node JS。 And things went pretty well. 事情进展顺利。 I saw an online tutorial and accepted GET request in my server.js file. 我在server.js文件中看到了一个在线教程并接受了GET请求。
Since I'm from a Java background, a few questions arrived into my mind and I searched them all over the Internet but could not find them out. 由于我来自Java背景,因此我想到了一些问题,我在Internet上进行了搜索,但找不到。
For Example: 例如:
var express=require("express");
var app=express();
app.get("/api/request1/",function(){
//some code here
})
app.get("/api/request2/",function(){
//some code here
})
.
.
.
.
app.get("/api/request100/",function(){
//some code here
})
This would make my code cumbersome and difficult to manage. 这会使我的代码繁琐且难以管理。 As I said I have a Java background and I used to separate my code in different Servlets. 就像我说的那样,我有Java背景,曾经用不同的Servlet来分隔代码。
Please specify some good resource or a technique how to overcome this issue. 请指定一些好的资源或技术来解决此问题。
You can easily modularize your express routes. 您可以轻松地将快递路线模块化。
To follow your example: in your project, create a directory routes
and a file routes/api.js
with the following contents: 遵循您的示例:在您的项目中,创建具有以下内容的目录routes
和文件routes/api.js
:
var express = require('express');
var router = express.Router();
router.get('/request1', function(req, res, next) {
res.send('...');
});
router.get('/request2', function(req, res, next) {
res.send('...');
});
module.exports = router;
And in your server.js
: 在您的server.js
:
app.use('/api', require('./routes/api'));
Just in case someone has the same question you can refer to the Express routing documentation 万一有人有相同的问题,您可以参考Express路由文档
app.get(...)
is just a function call. app.get(...)
只是一个函数调用。 You can easily do this: 您可以轻松地做到这一点:
require('routes1')(app);
require('routes2')(app);
where those modules export function(app) { app.get(...); app.get(...); }
这些模块在哪里导出function(app) { app.get(...); app.get(...); }
function(app) { app.get(...); app.get(...); }
Even better, Express.js (not Node.js - Node.js is like JVM, Express is like Tomcat) apps can mount subapps: 更好的是,Express.js(不是Node.js-Node.js就像JVM,Express就像Tomcat)可以挂载子应用程序:
app.use('/api', require('subapp'));
If subapp
is a normal Express.app with, say, app.get('/request1', ...)
, then, after mounting, you will have /api/request1
available to you. 如果subapp
是具有例如app.get('/request1', ...)
的普通Express.app,则在挂载后,您将可以使用/api/request1
。 (This only works for entire hierarchies; so if you want to split your /api/request1
... /api/request100
into ten files, you might want to use the first approach, or rethink how your hierarchy works.) (这仅适用于整个层次结构;因此,如果要将/api/request1
... /api/request100
拆分为十个文件,则可能要使用第一种方法,或者重新考虑层次结构的工作方式。)
是的,您应该与模块尽可能保持隔离,因为我看到您已经开始学习express do checkout express-generator模块,该模块为您提供一个不错的小型样板代码,在构造大型项目时也要从中开始列出Blog best-practices-express-结构以进行高级使用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.