Node.js module reference problem.

because there is too much startup file code, I want to write the routing code into the module folder.
but why does viewing the log return undefined,?

router.js file:

//router
const koa_router = require("koa-router");
//
const router = new koa_router();

module.exports.get= function() {
   router.get("/", (ctx, next) => {
        ctx.render("index");
         
   });
};

Startup file server.js: (other files are loaded differently, extract this part of the code)

      //
      k_router = require("Router"),
      //Koa
      app = new Koa(),
      //
      router = new koa_router();
      
      
      
      //
      k_router.get();
      console.log(k_router.get());  //undefined
      

is the module file written correctly?

Mar.31,2021

there is no return, in a function,. This function must return undefined when executed.
there is another point. The router and server.js set in your get method are not the same instance, so it is recommended that you

  1. or pass the router in server.js as an argument to the get method, and then the get method operates on the router.
  2. or get returns router,server.js and directly uses the router returned by get

//
k_router = require('Router'),

is there a problem with the loading custom module? if it is a custom module, it is recommended to use a relative or absolute path.
the writing in your code will be parsed into built-in modules or dependent module packages

Menu