Home > Software engineering >  Express.js : express() not a function error
Express.js : express() not a function error

Time:06-02

I'm learning express and running the code from the terminal gives me errors, below are my code and the terminal error prompt

const express = require("express");
const app = express();
app.listen(3000);

Terminal said:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'C:\Users\ENIOLA YUSUFF\desktop\my-express-server\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///C:/Users/ENIOLA YUSUFF/desktop/my-express-server/server.js:5:17    
←[90m    at ModuleJob.run (node:internal/modules/esm/module_job:197:25)←[39m        
    at async Promise.all (index 0)
←[90m    at async ESMLoader.import (node:internal/modules/esm/loader:337:24)←[39m   
←[90m    at async loadESM (node:internal/process/esm_loader:88:5)←[39m
←[90m    at async handleMainPromise (node:internal/modules/run_main:61:12)←[39m 

I tried using this code beneath instead thinking it was the difference in the node version but it solved half the problem.

import * as express from "express";
const app = express();
app.listen(3000);

Terminal error:

$ node server.js
file:///C:/Users/ENIOLA YUSUFF/desktop/my-express-server/server.js:2
const app = express();
            ^

TypeError: express is not a function
    at file:///C:/Users/ENIOLA YUSUFF/desktop/my-express-server/server.js:2:13    
    at ModuleJob.run (node:internal/modules/esm/module_job:197:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:337:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)

CodePudding user response:

Try This

import express from 'express';

const app = express();

CodePudding user response:

Please share your package.json. You probably have "type": "module" in the file. That's why you have to use import instead of require.

You should be able to use import express from "express" for it to work.

  • Related