You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HTML字符串发送至后端?NextJs+Axios场景下的问题咨询

解决富文本HTML内容通过Axios发送JSON格式报错的问题

核心原因

HTML内容中的双引号、换行符、制表符等特殊字符会破坏JSON语法结构,导致Axios序列化请求体时出错。以下是几种可行的解决方法:

方法1:对HTML内容进行URI编码

这是最直接的方案,通过encodeURIComponent将HTML转为URI安全的字符串,后端接收后再解码还原即可。

// 前端处理并发送请求
const htmlContent = editor.getContent(); // 替换为你的富文本编辑器输出方法
const encodedContent = encodeURIComponent(htmlContent);

axios.post('/api/save-content', {
  content: encodedContent
})
.then(res => {
  // 处理成功响应
})
.catch(err => {
  // 处理错误
});

// 后端解码(以Node.js为例)
const decodedContent = decodeURIComponent(req.body.content);

方法2:手动转义JSON特殊字符

如果不想用URI编码,可以手动替换HTML中干扰JSON的特殊字符:

const escapeHtmlForJson = (html) => {
  return html
    .replace(/\\/g, '\\\\') // 转义反斜杠
    .replace(/"/g, '\\"')   // 转义双引号
    .replace(/\n/g, '\\n')  // 转义换行符
    .replace(/\r/g, '\\r')  // 转义回车符
    .replace(/\t/g, '\\t'); // 转义制表符
};

const htmlContent = editor.getContent();
const escapedContent = escapeHtmlForJson(htmlContent);

axios.post('/api/save-content', {
  content: escapedContent
});

方法3:用Cheerio清理/规范HTML

Cheerio的作用是像jQuery一样解析和操作HTML,你可以用它去除冗余标签、修复未闭合标签,减少特殊字符的干扰,之后再配合编码发送:

import cheerio from 'cheerio'; // Next.js中使用import引入

const htmlContent = editor.getContent();
const $ = cheerio.load(htmlContent);

// 示例操作:移除可能带特殊字符的script、style标签
$('script, style').remove();
// 获取修复后的规范HTML
const cleanedHtml = $.html();

// 编码后发送请求
axios.post('/api/save-content', {
  content: encodeURIComponent(cleanedHtml)
});

额外建议

检查你使用的富文本编辑器是否自带转义输出功能,比如Quill的getText()(输出纯文本)、TinyMCE的getContent({format: 'text'}),部分编辑器还支持直接输出转义后的HTML,开启这类配置能从源头避免格式问题。

内容的提问来源于stack exchange,提问作者next951595

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:21:00