javascriptnode.jsexportnode-modules

SyntaxError: The requested module './routes/authRoutes.js' does not provide an export named 'default'


I am trying to implement endpoints for my book catalog using Node js and I could encounter thee below error when setting up the base urls.

index.js

    import express from 'express';
    import mongoose from 'mongoose';
    import connectDB from './config/db.js';
    import bookRoutes from './routes/bookRoutes.js';
    import authRoutes from './routes/authRoutes.js'; 
    
    const PORT = 3000;
    
    const app = express();
    app.use(express.json());
    connectDB();
    
    app.use('/auth', authRoutes);
    
    
    app.listen(PORT, (req, res) => {
        console.log(`Server is up and running in port ${PORT}`);
    })
    

authRoutes.js

import express from 'express';
import User from '../models/User.js';

const router = express.Router();

//Registration
router.post('/register', async (req, res) => {
    const {username, password} = req.body;
    try{
        const user = new User({username, password});
        await user.save();
    }catch(err){
        alert(err);
        res.send(401).send('Error occurred while registering the new user');
    }
    res.status(200).send('User registered.')
});

//Login
router.post('/login', async (req, res) => {
    const{username, password} = req.body;
    const user = await User.findOne({username});

    if(!user || user.password !== password){
            return res.status(401).send('Invalid username or password');
    }
    res.status(200).send('login successful');
});

module.exports = router;

Can someone please point to what I am missing?

Thank you in advance!


Solution

  • It looks like you're trying to use import/export syntax, but in your final line, you're using module.exports. In ES modules, you should consistently use export and import throughout your code.

    Export Statement: Changed module.exports = router; to export default router;.