ReferenceError: path is not defined:Express

64

页面已渲染,但当我点击任何链接时会出现错误。

ReferenceError: path is not defined
at app.get (/var/www/example.com/example-domain/server.js:106:19)
at Layer.handle [as handle_request] (/var/www/example.com/example-domain/node_modules/express/lib/router/layer.js:95:5)
at next (/var/www/example.com/example-domain/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/var/www/example.com/example-domain/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/var/www/example.com/example-domain/node_modules/express/lib/router/layer.js:95:5)
at /var/www/example.com/example-domain/node_modules/express/lib/router/index.js:281:22
at param (/var/www/example.com/example-domain/node_modules/express/lib/router/index.js:354:14)
at param (/var/www/example.com/example-domain/node_modules/express/lib/router/index.js:365:14)
at Function.process_params (/var/www/example.com/example-domain/node_modules/express/lib/router/index.js:410:3)
at next (/var/www/example.com/example-domain/node_modules/express/lib/router/index.js:275:10)

这是来自 server.js 的代码:

app.use(express.static('../build'));
app.get('*', (req, res)=> {
  const index = path.join(__dirname, '/', '../build', 'index.html' );
  res.sendFile(index);
});

提前感谢。

4个回答

151
在文件头部,只需添加

const path = require('path');

使用NodeJS 18,路径似乎可以在不需要引用它的情况下定义。但是ESLint仍然会发出警告。 - Marc

20

你需要使用 path 模块吗?

const path = require('path')

0
你需要在文件中引入Path模块,引入Path模块的语法如下:
const path = require('path');

0
在你的代码头部写下这行代码。这行代码导入了内置的Node.js路径模块,该模块提供了用于处理文件和目录路径的实用工具。
通过引入路径模块,你可以使用它的方法以一种安全且跨平台兼容的方式来操作文件路径。
const path = require('path');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接