简体   繁体   中英

How to call a function (in separate file) from http callback function. app.get("/", callbackFun)

File structure:

testAPI
    contactDetail
        dispMobNo.js
        myModule.js
index.js

index.js

const express = require("express");
const app = express();
const port = process.env.port || 3000;
const getCustNo = require("./contactDetail/dispMobNo");
app.use(getCustNo);

app.listen(port, console.log("server running on port: " + port));

dispMobNo.js

const express = require("express");
const router = express.Router();
router.get("/", getContactNo);

function getContactNo(req, res)
{
    console.log(req.query);
    res.send(req.query);
}
module.exports = router;

Above code is working BUT I want to remove getContactNo function from this file and want to put it in a separate file. I mean, I don't want to put any code inside/under API endpoint. I want to put getContactNo function in separate file and want to call from API endpointcallback function. So, how to do this?

Modified version of dispMobNo.js:

const express = require("express");
const router = express.Router();
router.get("/", getContactNo);
module.exports = router;

myModule.js

function getContactNo(req, res)
{
    console.log(req.query);
    res.send(req.query);
}
module.exports = getContactNo;

you can do this way

  1. create one controller file in which create and export all your business logic functions.

 // controller.js file export async getData = (req,res) => { // your logic }

  1. import that controller file in your route file, and use function there.

 // route.js file const Controller = require("./controller"); route.get('/api-endpoint',async(req,res)=>{ Controller.getData(req,res); })

EDIT for simpler explanation

// controller.js file
function getData(req,res){
 //your logic
}
module.exports = {getData}
    
// main route file
const {getData} = require('./controller.js');
 route.get('/api-endpoint',function(req,res){
getData(req,res);
});

You are almost there.

Modified version of dispMobNo.js:

const myModule = require('./my-module.js');
const express = require("express");
const router = express.Router();
router.get("/", myModule.getContactNo);
module.exports = router;

my-module.js

function getContactNo(req, res)
{
    console.log(req.query);
    res.send(req.query);
}
module.exports = {
  getContactNo
};

Above, I have assumed that, both files are in same directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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