Calling api express function from another file (NodeJS)

Hi. I have made an app that has a working api functions. I’m also adding swagger page for it and all works fine if all of these functions are in the same page. Though all of this looks very messy as there’s a lot of them, so i’m wondering how to divide these settings into different files and be able to call them?

For example i have hello world as “/” page to make sure it’s on and the function looks like this:

app.get('/', (req, res) => {

res.send('Hello from App Engine!');


How would i make the function so i can call this one from another file, say “apiFunctions.js” file?

You can extract router instance:

// routes.js
const { Router } = require('express');

const router = Router();

router.get('/', handleRouting);

module.exports = router;

The in the main file:

// main.js
const express = require('express');
const router = require('./routes.js');

const app = express();

app.use('*', router);

@snigo is correct.

You can also use this router to make a modular type of API.

For example, you have a “/user” in your API and you want to have a “/login”.

All of the routes that are related to a user should be made in users-routes.js file

you can do:

const { Router } = require(‘express’);

const router = Router();’/login’, “what you want to do”);

module.exports = router;

and in the app.js or main.js file you can do:
const userRoute= require(’./users-routes.js’);
app.use(’/user’, userRoute) --> all routes in the users-route.js will be called with “/user”. example is “/user/login”

Thanks to both of you, this cleared it up a lot :slight_smile: