Home > database >  What is wrong with my code? Why can't i import the router?
What is wrong with my code? Why can't i import the router?

Time:11-28

The error says: 'Error [ERR_MODULE_NOT_FOUND]: Cannot find module '...\server\router\index' imported from \server\index.js

I think i did correct import. I use "type":"module" in package.json. How can i fix this? enter image description here index

import dotenv from 'dotenv'
import express from 'express'
import cors from 'cors'
import mongoose from 'mongoose'
import cookieParser from 'cookie-parser'
import { router } from './router/index'

dotenv.config()

const PORT = process.env.PORT || 7000
const app = express()

app.use(express.json())
app.use(cookieParser())
app.use(cors())
app.use('/api', router)

const start = async () => {
  try {
    await mongoose.connect(process.env.DB_URL, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    app.listen(PORT, () => console.log(`Server started on ${PORT} port`))
  } catch (e) {
    console.log('Connection error', e)
  }
}
start()

router

const express = require('express')
import userController from '../controllers/user-controller'

const router = express.Router()

router.post('/registration', userController.registration)
router.post('/login', userController.login)
router.post('/logout', userController.logout)
router.get('/activate/:link', userController.activate)
router.get('/refresh', userController.refresh)
router.get('/users', userController.getUsers)

export { router }

CodePudding user response:

You have to export deafult {router} in /router module

And in your entry file (index.js) you have to import it like this:

import {router} from './router' without router/index

CodePudding user response:

Finally in router export { router }

in index import { router } from './router/index.js'

  • Related