Node.js Express readFile html和replace string返回空白页
我正在使用Express中的Node.js Express readFile html和replace string返回空白页,node.js,express,Node.js,Express,我正在使用Express中的fs.readFileAPI来读取html文件,我想替换html文件中的字符串,但它在客户端返回一个空白页。 我的目录结构是: // ===== directory ===== // rootDir dist/ index.html index.js package.json // ==== package.json ==== // { "name": "express", "version": "1.0.0", "main":
fs.readFile
API来读取html文件,我想替换html文件中的字符串,但它在客户端返回一个空白页。
我的目录结构是:
// ===== directory ===== //
rootDir
dist/
index.html
index.js
package.json
// ==== package.json ==== //
{
"name": "express",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"private": true,
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.16.3"
}
}
// ==== dist/index.html ======//
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Some Title</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
// ==== index.js ==== //
const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
const PORT = 3000;
app.use(express.static('dist'));
fs.readFile(path.resolve(__dirname, 'dist/index.html'), (err, data) => {
if (err) throw err;
const lorem = 'lorem ipsum';
const test = data.toString().replace('<div id="app"></div>', `<div id="app">${lorem}</div>`)
// doing console.log for testing
console.log(test)
// returning variable
// return test
});
app.get('/', (req, res) => {
res.render('index.html')
})
app.listen(PORT, (error) => {
console.log(`listening port ${PORT}`);
})
没有错误,但为什么我有一个空白页?有什么建议或帮助吗
谢谢发生这种情况是因为,当您执行
fs.readFile
时,您不会将结果存储在任何地方。当您返回测试时代码>,则该值不存在
要解决您的问题,请删除此无用的fs.readFile
部分,并在路由器中指定'dist/index.html',如下所示:
// ==== index.js ==== //
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.static('dist'));
app.get('/', (req, res) => {
res.render('dist/index.html');
});
app.listen(PORT, error => {
console.log(`listening port ${PORT}`);
});
这应该行得通
// ==== index.js ==== //
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.static('dist'));
app.get('/', (req, res) => {
res.render('dist/index.html');
});
app.listen(PORT, error => {
console.log(`listening port ${PORT}`);
});