我正在努力创建一个博客网站。用户将使用文本编辑器创建一个新博客(我使用的是Ckeditor5)。我想要的是用户可以将图像插入到他或她想要的任何地方。当我检查 JSON 时,我成功地将帖子上传到服务器,它返回了类似这样的内容。
{
"id": 12,
"title": "bài viết số 12",
"text": "<p>`12131441411âfafafa</p><p><img src=\"null\"></p>",
"time_created": "2024-03-03T14:34:34.090+00:00",
"time_updated": null,
"post_background_img": null,
"views": null,
"user": {
"id": 1,
"username": "john_doe",
"email": "[email protected]",
"password": "$2a$12$VbU4xpQPAwrtnpPXZWB/0.J7pY6py/E04k2n5i23cL5hom.Zi85A6",
"avatar": "http://example.com/avatar.jpg",
"ban": false
},
"comments": []
}
它将标签插入文本中, 那么如何在reactjs中将其渲染回正常的HTML,我在Google上搜索过,我可以使用
dangerous HTML,
,但它非常不安全。有什么方法可以实现我想要的,第二件事是当我将图像发布到服务器时它返回 null
这是我用来上传的代码片段
async function handleSubmit(e) {
e.preventDefault();
// Create the blog post object
const newBlog = {
title,
slug,
text: content,
};
// Post the blog data to the server
const userID = 1; // Replace with actual userID
const response = await fetch(
`https://englishforum.zeabur.app/api/v1/posts/user/${userID}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newBlog),
}
);
if (response.ok) {
console.log("Blog post created successfully:", newBlog);
// You might want to redirect the user or show a success message here
} else {
console.error("Failed to create blog post");
// Handle error scenario
}
}
使用 DOMPurify 清理危险的 HTML 并防止 XSS 攻击。 DOMPurify 允许您清理充满脏 HTML 的字符串,返回干净的 HTML。这对于确保网站上动态生成的内容的安全非常有用。在 GitHub 上了解更多信息。
DOMPurify 净化 HTML 并防止 XSS 攻击。您可以向 DOMPurify 提供充满脏 HTML 的字符串,它将返回一个包含干净 HTML 的字符串(除非另有配置)。
// Assuming `response.text` contains the dirty HTML
const clean = DOMPurify.sanitize(response.text);
使用
clean
变量来获取安全的 HTML 内容。