关于Nodejs输出html文本的问题
关于Nodejs输出html文本的问题
刚学习后台程序,看上了nodejs。在用nodejs取数据的时候,出现了这样的情况,取的mysql里的数据,字段里的内容包含一些html标签,比如《p》<p><br>一类的,但输出的时候<自动变成了<这样的符号,就不能正确的解析了。这个要怎么解决呢?
<div class = "span4">
<%=(results.tc_description) %>
</div>
6 回复
在使用 Node.js 输出 HTML 文本时,如果直接将包含 HTML 标签的字符串插入到 HTML 中,浏览器会自动转义这些字符,导致 HTML 标签无法正确解析。为了解决这个问题,你可以使用 toString()
方法或者专门的库如 he
(HTML entities)来处理。
示例代码
使用 toString()
方法
const express = require('express');
const mysql = require('mysql');
const app = express();
// 创建 MySQL 连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'yourusername',
password: 'yourpassword',
database: 'yourdatabase'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to the MySQL server.');
});
app.get('/', (req, res) => {
const query = 'SELECT * FROM your_table';
connection.query(query, (err, results) => {
if (err) throw err;
// 输出带有 HTML 标签的文本
res.send(`
<div class="span4">
${results[0].tc_description.toString()}
</div>
`);
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
使用 he
库
首先需要安装 he
库:
npm install he
然后可以这样使用:
const express = require('express');
const mysql = require('mysql');
const he = require('he');
const app = express();
// 创建 MySQL 连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'yourusername',
password: 'yourpassword',
database: 'yourdatabase'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to the MySQL server.');
});
app.get('/', (req, res) => {
const query = 'SELECT * FROM your_table';
connection.query(query, (err, results) => {
if (err) throw err;
// 解码 HTML 实体
const decodedDescription = he.decode(results[0].tc_description);
// 输出带有 HTML 标签的文本
res.send(`
<div class="span4">
${decodedDescription}
</div>
`);
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
解释
-
toString()
方法:- 直接调用
toString()
方法可以确保字符串中的 HTML 标签不会被转义。
- 直接调用
-
he
库:he
是一个用于处理 HTML 实体的库。he.decode()
方法可以将 HTML 实体(如<
转换为<
)解码为原始字符。- 这样可以确保从数据库中取出的 HTML 内容能够正确地显示在页面上。
通过以上方法,你可以确保从数据库中获取的包含 HTML 标签的文本能够正确地在网页中显示。
<div class = "span4">
<%-(results.tc_description) %>
</div>
好像事这样,你看下api,我一直事用的jade
Escapes html by default with <%= code %>
Unescaped buffering with <%- code %>
果然如此啊,=换成-就可以了,新手,连api都不知道怎么查,而且是用sublime写代码,代码提示也没有。原来是写as3的,现在各种不习惯啊
谢谢解惑