javascript - TypeError:无法将对象转换为原始值
问题描述
我有一个文本编辑器(div),并且有一个功能可以格式化其中的(选定)文本。当我标记文本的一部分并选择使其看起来像this
(代码片段)时,我必须使用
它来避免一些错误并使其对用户友好。但是,此数据正在发送到服务器(nodeJS),它会导致内容拆分为对象的错误,为了避免此问题,我想
在将其发送到服务器之前用空格替换。
我所做的是以下
// replace by " "
let content = $('.editor').html().replace(/( )/gi, " ");
// replace editor html
$('.editor').html(content);
// print results
console.log("html: ",$('.editor').html());
在控制台中,它显示预期的内容(文本:)as <code>dasdasd</code>
:
html: as<span> </span><code>dasdasd</code><span> </span>
但是在服务器端我收到以下错误:
TypeError: Cannot convert object to primitive value
然后我决定打印包含编辑器内容的变量(这看起来不错?):
{ posterContent: 'as<span> </span><code>dasdasd</code><span> </span>' }
问题:如何
用空格替换而不必将 html 转换为(字符串)以避免此错误?
解决方案
我知道你解决了这个问题,但你可能有兴趣阅读这篇文章,因为你的问题源于一个被误解的 web 开发的基本概念,即数据编码。
据我了解,您不能将字符串传递
到后端,因为它被解析为对象,所以我假设您使用 GET 或 POST 的application/x-www-form-urlencoded
编码来发送请求。简单来说:
// this object
{
a: 10,
b: 20
}
// get passed to the server as this string
a=10&b=20
这很好。这是一种方法。但是您必须处理发送特殊字符的正确编码,例如:
// you have this object:
{
a: 10,
b: 'hello&world'
}
// you encode it naively to this
a=10&b=hello world
// the server understands this
{
a: 10,
b: 'hello',
nbsp: ';world'
}
会&
创建错误,因为它是一个特殊字符,不会被视为字符串的一部分。即使你找到了不使用的技巧 
,或者用空格替换它,你也会认为你已经解决了问题,但是......几乎所有的unicode字符都是特殊字符,需要进行编码以免产生错误.
使用 编码您的字符串encodeURIComponent
,或使用不同的编码(例如 JSON)发布您的数据。我个人会使用这样的功能fetch
,它可以为您完成所有工作,并为您免除所有与编码相关的问题:
let data = {
userId: 1,
id: 1
}
fetch('https://jsonplaceholder.typicode.com/posts',{
method: 'POST',
data: JSON.stringify(data)
})
.then(resp => resp.json())
.then(json => console.log(json));
推荐阅读
- android - 它当前正被另一个 Gradle 实例使用。,这是一个 android studio 问题或 mac Mojave 权限
- api - 我们如何设计 .net core api 控制器来接受字符串的数组值
- php - 如何匹配以下正则表达式
- firebase - 为什么我在 Firebase Cloud Functions 中收到“无效信封”错误?
- c# - 尝试返回 bool 时使用未分配的局部变量
- android-studio - 如何在 Android Studio 的包中添加新目录/文件夹
- express - 在 Express 中使用 supertest 时如何模拟 redis?
- linux - SECTION .DATA 中存在变量的分段错误
- php - 循环遍历 html 表并使用简单的 dom 解析器在 php 中获取 tr、th 和 td
- c# - 如何在 Asp.net C# 的另一个页面上显示 ViewDetail