[英]How to add Express route endpoints from another .js file?
I have an Express app whose server.js
file has maybe 30 GET and POST endpoints, like this:我有一个 Express 应用程序,其
server.js
文件可能有 30 个 GET 和 POST 端点,如下所示:
const express = require('express');
const app = express();
const http_port = 8000;
app.listen(http_port,()=>{
console.log(`app listening on port ${http_port}`);
});
app.get('/create_something',function(req,res){
createSomething();
res.send('create');
});
app.post('/update_something',function(req,res){
updateSomething();
res.send('update');
});
//and so on for 30 more endpoints
For ease of maintenance, I want to break this set of endpoints up into different files, eg video.js
and audio.js
.为了便于维护,我想将这组端点分成不同的文件,例如
video.js
和audio.js
。
Thinking this solution might help, I created another file other_route.js
:认为这个解决方案可能会有所帮助,我创建了另一个文件
other_route.js
:
var express=require('express');
var router=express.Router();
router.get('/other_route_endpoint',function(req,res){
res.send('other_route_endpoint');
});
module.exports.router=router;
and then including this in server.js
by changing my initial declarations to:然后通过将我的初始声明更改为将其包含在
server.js
中:
const express = require('express');
const app = express();
const http_port = 8000;
var router=express.Router();
router.use('/other_route',require('./other_route').router);
But when I visit myserver.com:8000/other_route_endpoint
, I get this error:但是当我访问
myserver.com:8000/other_route_endpoint
,我收到此错误:
Cannot GET /other_route_endpoint
How can I add in endpoints from other files into server.js
, so I can move some of its many endpoints into these subfiles?如何将其他文件中的端点添加到
server.js
,以便我可以将其许多端点中的一些移动到这些子文件中?
First, your main file should not be using a router.首先,您的主文件不应该使用路由器。 Change the line to
app.use('/other_route',require('./other_route').router);
将该行更改为
app.use('/other_route',require('./other_route').router);
. .
Second: each path you set with router.use
in the routing file will be relative to the path specified in app.use
.第二:您在路由文件中使用
router.use
设置的每个路径都将相对于app.use
指定的路径。 See https://expressjs.com/en/guide/routing.html#express-router见https://expressjs.com/en/guide/routing.html#express-router
For example, if you have this in your main file例如,如果您的主文件中有这个
app.use('/foo', require('./bar.js'));
And this in bar.js
这在
bar.js
router.get('/bar', /* do something */);
Then the corresponding endpoint would be /foo/bar
.那么相应的端点将是
/foo/bar
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.