Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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, e.g. video.js and audio.js.

Thinking this solution might help, I created another file 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:

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:

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?

like image 301
sigil Avatar asked Oct 26 '25 07:10

sigil


2 Answers

First, your main file should not be using a router. Change the line to 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. See 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

router.get('/bar', /* do something */);

Then the corresponding endpoint would be /foo/bar.

like image 169
Ryan Avatar answered Oct 28 '25 22:10

Ryan


First, your main file should not be using a router. Change the line to 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. See 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

router.get('/bar', /* do something */);

Then the corresponding endpoint would be /foo/bar.

like image 33
Ryan Avatar answered Oct 28 '25 21:10

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!