简体   繁体   中英

TypeError: express.Router is not a function in Node.js

when I tried to run my app by npm start the I got the error:

export const router = express.Router();
^

TypeError: express.Router is not a function
at file:///C:/Users/hassa/notes/routes/index.mjs:4:31

The code of my index.mjs file is:

import * as express from "express";

import { NotesStore as notes } from "../app.mjs";

export const router = express.Router();
 /* GET home page. */
router.get("/", async (req, res, next) => {
 try {
   const keylist = await notes.keylist();
  // console.log(`keylist ${util.inspect(keylist)}`);
  const keyPromises = keylist.map((key) => {
  return notes.read(key);
});
const notelist = await Promise.all(keyPromises);
// console.log(util.inspect(notelist));
res.render("index", { title: "Notes", notelist: notelist });
} catch (err) {
  next(err);
}
});

I have already seen other questions with similar topic on stackoverflow but I did not get any solution. If anybody knows how to solve it then please let me know. Thanks.

import * as express from "express";

import { NotesStore as notes } from "../app.mjs";    
const router = express.Router();
     /* GET home page. */
    router.get("/", async (req, res, next) => {
     try {
       const keylist = await notes.keylist();
      // console.log(`keylist ${util.inspect(keylist)}`);
      const keyPromises = keylist.map((key) => {
      return notes.read(key);
    });
    const notelist = await Promise.all(keyPromises);
    // console.log(util.inspect(notelist));
    res.render("index", { title: "Notes", notelist: notelist });
    } catch (err) {
      next(err);
    }
    });
export router;

Try like this.

I think the problem lies with the way you import express into your file. To import express, you would want a default import rather than a named import. In this case, instead of import * as express from 'express' , change it to import express from 'express' or import {default as express} from 'express' and you should be good.

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