【问题标题】:res.sendFile not rendering htmlres.sendFile 不呈现 html
【发布时间】:2019-11-28 02:08:19
【问题描述】:

我正在尝试使用绝对路径使用 res.sendFile 呈现 HTML,但它在 pre 标记中发送编码的 HTML,因此响应显示 HTML 未在 pre 标记中呈现。 这是我的快速代码

app.get('/', (req,res) =>{
        res.sendFile(__dirname+'/a.html');
    });

这是我的html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>I am Html</h1>
</body>
</html>

这是我导航到 localhost:8800/ 时的结果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>I am Html</h1>
</body>
</html>

它按原样打印html而不渲染它。

【问题讨论】:

  • 您是否明确在某处为响应设置标题。例如,在具有 res.setHeader("Content-Type", "text/plain"); 之类的全局中间件中,这可能是一个原因。虽然没有意义(因为支持的版本是 5 年前出现的),但你使用的是 express 版本 > 4.8.0 ?
  • 其实,是的。这一直是问题所在。感谢您的帮助

标签: html node.js express


【解决方案1】:

您需要使用 res.render() 来实际渲染 html。

【讨论】:

  • 如果我没记错 res.render 用于模板引擎
【解决方案2】:

我无法发表评论,因为我没有足够的声誉,但我想说的是我在我的系统上运行了你的代码(OSX Mojave 10.14.6,Node v12.13.0,最新版本的Firefox 和 Chrome)添加了一些功能以使其正常工作(发布在下面),并且没有遇到您的问题。也许您还有一些其他代码或中间件尚未发布。另外,res.render 用于模板是正确的。

const express = require('express');
const app = express();
const port = 3000;
const path = require('path');

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/a.html');
    // better to use the path API, but both work
    // res.sendFile(path.join(__dirname, 'a.html'));
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

HTML 是一样的。文件夹结构为:

.
├── app.js
├── a.html

您能发布更多详细信息吗?

【讨论】:

  • 我想通了。这是一个头中间件问题
猜你喜欢
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
  • 2020-07-26
  • 2021-08-20
  • 2012-10-06
  • 2016-08-22
相关资源
最近更新 更多