我一直在尝试创建自己的博客应用程序,用户可以在其中创建帖子,并且我设法插入了 Quill 富文本编辑器。
它成功更新了一段状态,但我收到的数据是 HTML 标记(示例如下)。所以我的问题是:如何使用 POST 请求将其保存到我的数据库中。
注意: 我不是问如何制作它的后端逻辑或如何进行 AJAX 调用,我只是问如何将此标记作为参数传递给 POST 请求。我是否需要某种转换器,以便可以将 HTML 标记转换为 JSON 对象或其他对象?
<h1>This is the header.</h1><p>This is a sample text </p><p>so you guys can have an idea of what </p><p>the editor produces and what I'm kind of </p><p>struggling to store in the MongoDB database.</p><p><em>and this is some italic text.</em></p>
当您已经获取数据时,您应该探索 React 中的一个选项
你的功能应该是:
function createMarkup(theExactHtmlWithTag) {
return { __html: theExactHtmlWithTag };
}
使用时:
<div dangerouslySetInnerHTML={createMarkup(`<h4> Hello <strong> World </strong></h4>` )} />
记住在数据库存储之前清理 HTML。
当我们使用像React Quill这样的富文本编辑器时,我们输入的内容以HTML格式存储,允许我们使用dangerouslySetInnerHTML来显示它。为了将此内容保存在 MongoDB 数据库中,我们将使用 Axios POST 方法将其发送到后端服务器。在服务器中,我们将创建一个模型来定义我们要存储的数据的结构,然后将此数据保存到数据库中。
import React, { useState } from "react";
import Axios from "axios";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import css from "./Editor.module.css";
const Editor = ({ questionId }) => {
const [value, setValue] = useState("");
const handleSubmitClick = async () => {
const response = await Axios.put(
`http://localhost:5000/expertsubmit/${questionId}`,
{
answer: value,
}
);
console.log("Expert content saved successfully:", response.data);
} catch (error) {
console.error("Error saving content:", error);
}
};
const modules = {
toolbar: [
[{ header: [1, 2, 3, 4, 5, 6, false] }],
["bold", "italic", "underline", "strike", "blockquote"],
[{ font: [] }],
[{ size: [] }],
[
{ list: "ordered" },
{ list: "bullet" },
{ indent: "-1" },
{ indent: "+1" },
],
["image"],
[{ color: [] }, { background: [] }], // dropdown with defaults from theme
[{ align: [] }],
["clean"],
],
};
return (
<>
<div className={css.editor}>
<ReactQuill
theme="snow"
value={value}
onChange={setValue}
className={css.editorInput}
modules={modules}
/>
{/* <div dangerouslySetInnerHTML={{ __html: value }}></div> */}
</div>
<div className={css.submitBtnContainer}>
<button onClick={handleSubmitClick} className={css.SubmitBtn}>
Submit my Answer
</button>
</div>
</>
);
}; `
现在让我们实现后端逻辑来存储数据,
app.put("/expertsubmit/:id",async (req, res) => {
const { answer } = req.body;
const { id } = req.params; // Extract ObjectID from request parameters
try {
// Find the document by its ObjectID and update it
const updatedContent = await Asset.findByIdAndUpdate(id, {
answer,
}, { new: true });
if (!updatedContent) {
// If the document with the given ObjectID doesn't exist
return res.status(404).json({ error: "Content not found" });
}
console.log("Expert HTML content updated successfully");
res.json({ message: "Expert HTML content updated successfully" });
} catch (error) {
console.error("Error updating HTML content:", error);
res.status(500).json({ error: "Internal server error" });
}
};
请注意:我在这里使用了 put 方法来更新数据库内容,您也可以使用 POST 方法。
谢谢你。