-1

I'm stuck in this error...I'm trying but I can not fix it This is my index.js file

import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";

const app = express();
dotenv.config();
const connect = async () => {
    try {
      await mongoose.connect(process.env.MONGO);
      console.log("Connected to mongoDB.");
    } catch (error) {
      throw error;
    }
  };
  mongoose.connection.on("disconnected", () => {
    console.log("mongoDB disconnected!");
  });

  app.listen(3000, () => {
    connect();
    console.log("Connected to backend.");
  });

This is my pacakge.json file

{
  "name": "quiz-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.0.2",
    "express": "^4.18.1",
    "mongoose": "^6.5.4"
  },
  "devDependencies": {
    "webpack-cli": "^3.3.12"
  }
}

when I run this app it shows this error

enter image description here

1 Answers1

0

You are using ES6 style importing import express from "express"; but your package.json doesn't know about that. Because the default is CommonJS for Node.js right now. And that means it wants you to use const express = require("express");

If you want to change that to ES6, you need to add "type": "module", in your package.json.

For example:

  ...
  "description": "",
  "type": "module",
  "main": "index.js",
  ...
sha'an
  • 1,032
  • 1
  • 11
  • 24