我一直在寻找如何获取 HTML 页面的基本 URL,以便来自浏览器的相对 URL 请求使用该基本 URL。
答案在这里 Defining root of HTML in a folder within the site root folder
从服务器呈现 HTML 时 - 是否有可靠的方法来添加 <base>
元素到 HTML?
HTML 文件是自动生成的,我不想手动添加 <base>
标记到文件,如果我能避免的话。当页面呈现时,以某种方式动态添加它会很好。
下面是 HTML 的原样:
<head>
<title>Code coverage report for All files</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="prettify.css" />
<link rel="stylesheet" href="base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(sort-arrow-sprite.png);
}
</style>
</head>
我想在使用服务器渲染时添加一个基本标签,所以它看起来像:
<head>
<title>Code coverage report for All files</title>
<meta charset="utf-8" />
<base href="http://localhost:3050/coverage/lcov-report/cdt-now/index.html"> // <<<<
<link rel="stylesheet" href="prettify.css" />
<link rel="stylesheet" href="base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(sort-arrow-sprite.png);
}
</style>
</head>
我想问题是 index.html 文件不在我的项目的根目录中:
但是 index.html 文件发出相对路径请求,正如您在 <link>
中看到的那样<head>
中的标签以上。
我目前正在呈现这样的页面:
router.get('/', ac.allow('Admin'), function (req, res, next) {
let html = path.resolve(__dirname + '/../coverage/lcov-report/cdt-now/index.html');
res.setHeader('content-type', 'text/html');
fs.createReadStream(html).pipe(res);
});
最佳答案
因此,使用我当前将响应流式传输到浏览器的代码的方法是:
const replacestream = require('replacestream');
router.get('/', ac.allow('Admin'), function (req, res, next) {
let html, val = 'coverage/lcov-report/cdt-now/index.html';
try {
html = path.resolve(__dirname + `/../${val}`);
fs.existsSync(html)
}
catch (err) {
return next(err);
}
res.setHeader('content-type', 'text/html');
let replacement = `</title><base href="http://localhost:3050/${val}">`;
fs.createReadStream(html).pipe(replacestream('</title>', replacement)).pipe(res);
});
这是基本思想。
关于javascript - 在服务器端渲染动态修改 <base> 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44575568/