简体   繁体   English

如何从另一个 .js 文件添加 Express 路由端点?

[英]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.jsaudio.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-routerhttps://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.

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