node.js - 发送html页面给客户端

标签 node.js express

我形成 html 页面的标记并写入变量 htmlToSend

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hyperspotters</title>
</head>
    <body style="margin: 0;
    font-family: Arial, Helvetica, sans-serif;">
            <header>
                <div style="background: #3366CD; padding: 10px">
                ....

我需要将其退还给客户。

我是这么宣传的

            let htmlToSend = func.statusСheck(success, replacements);
            return res.sendFile(htmlToSend);

            let htmlToSend = func.statusСheck(success, replacements);
            return res.render(htmlToSend);

如何将我的标记返回给客户?

最佳答案

通常,Express.js 的中间件函数会公开 reqres 对象,其中 res 是响应对象,您可以用它来将响应发送回客户端。

示例:

app.use(function (req, res, next) {

});

正如 @jacob 所说,使用响应对象的 send 函数向客户端发送回复。但是,您应该将数据作为字符串(而不是缓冲区)发送,因为使用缓冲区会导致数据被解释为二进制数据,但显然您正在发送文本。另外,使用缓冲区会使 Express 设置“application/octet-stream”的 Content-Type,这也不是您想要的。相反,将其设置为“text/html”。

app.use("/", function (req, res, next) {
   res.set('Content-Type', 'text/html');
   res.send(htmlToSend);
});

参见:http://expressjs.com/en/guide/routing.html
还有:https://expressjs.com/en/4x/api.html#res.send

关于node.js - 发送html页面给客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55512543/

相关文章:

node.js - 如何刷新nodejs child_process stdin.write

authentication - Socket.IO 认证

javascript - 在 Node.js 中,变量的赋值

node.js - Nodejs 中所有路由之后的中间件

javascript - NodeJS + ExpressJS 压缩什么都不做?

Node.js url 路由格式化

javascript - Jest/eslint 中函数缺少返回类型

javascript - Node JS 异步数据库调用

json - Azure 网站实例未运行 Package.json 中定义的 Node 版本

node.js - 在不提供 SSL 证书的情况下运行 Node.js HTTPS 服务器?