[英]Express.js : express() not a function error
I'm learning express and running the code from the terminal gives me errors, below are my code and the terminal error prompt我正在学习 express 并且从终端运行代码给了我错误,下面是我的代码和终端错误提示
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%20YUSUFF/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%20YUSUFF/desktop/my-express-server/server.js:2
const app = express();
^
TypeError: express is not a function
at file:///C:/Users/ENIOLA%20YUSUFF/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)
Try this:尝试这个:
import express from 'express';
const app = express();
You probably have "type": "module"
in the file.您可能在文件中有
"type": "module"
。 That's why you have to use import
instead of require
.这就是为什么你必须使用
import
而不是require
。
You should be able to use import express from "express"
for it to work.您应该能够使用
import express from "express"
来使其工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.