Home > Back-end >  Importing express router from es6 module
Importing express router from es6 module

Time:12-03

this is my first nodeJS project and im getting stuck already. In the package.json "type" = "module". I keep getting an error "ERR_MODULE_NOT_FOUND". I tried default and named export but both didnt work.

productRoutes.js

import express from 'express';

const router = express.Router();

router.get('/', (req, res) => {
  res.status(200).json({ msg: 'get products' });
});

export default router;

server.js

import 'dotenv/config';
import express from 'express';
import mongoose from 'mongoose';
import routes from './api/v1/routes/productRoutes';

// express app
const app = express();

// middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use((req, res, next) => {
  console.log(req.path, req.method);
  next();
});

// routes
app.use('/api/products', routes);

// connect to db
mongoose
  .connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log('connected to database');
    // listen to port
    app.listen(process.env.PORT, () => {
      console.log('listening for requests on port', process.env.PORT);
    });
  })
  .catch((err) => {
    console.log(err);
  });

CodePudding user response:

If you don't provide extension of a js file .js the node compiler doesn't understand it, unless you use some other transpilers like babel.

so change import routes from './api/v1/routes/productRoutes'; to import routes from './api/v1/routes/productRoutes.js';

  • Related