简体   繁体   中英

Node.js express.Router ERR_MODULE_NOT_FOUND when import the new routes

I am experiencing a weird error. I was just creating a new folder to separate my routes.

Inside I created the routes using the express.Router API and I exported the router itself.

Here is how the code looks like inside post-routes.ts :

import express from 'express';

const router = express.Router();

router.get( '/', ( req, res ) =>
{
    res.send( 'This is working' );
} );

export default router;

Ok. All I have to do now is to import it inside my index.ts and create a root route for my post-routes.ts file.

Please tell me if you see something wrong in my approach.

index.ts file:

import express from 'express';
import cors from 'cors';
import postRouter from './routes/post-routes';

const PORT = process.env.PORT || 5000;

app.use( '/posts', postRouter );


app.use( express.json( { limit: '30mb' } ) );
app.use( express.urlencoded( { limit: '30mb', extended: true } ) );
app.use( cors() );

app.listen( PORT, () => console.log( `listening at ${ PORT }` ) );

Good. Now to offer as much information as I possibly can, I will insert the following:

  1. File structure inside my project:

文件结构

  1. package.json file configuration:

包.JSON 文件

As you can see, I am using the "type": "module" to be able to use import inside my node application. As for the typescript, I am getting no compiling errors, so index.ts sees the post-routes.ts file so I would expect that index.js would see post-routes.js file as well. But the server throws the error below. How can this be?

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'E:\Github\hospytal-fasion\server\dist\routes\post-routes' imported from E:\Github\hospytal-fasion\server\dist\index.js

Apart from making sure that target and module are set to esnext in your tsconfig.json , make sure to include file extensions in your imports. ie try changing the following line:

import postRouter from './routes/post-routes';

to

import postRouter from './routes/post-routes.ts';

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