我形成 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
的中间件函数会公开 req
和 res
对象,其中 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/