首页 > 解决方案 > 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>' }

问题:如何&nbsp;用空格替换而不必将 html 转换为(字符串)以避免此错误?

标签: javascriptjquerynode.js

解决方案


我知道你解决了这个问题,但你可能有兴趣阅读这篇文章,因为你的问题源于一个被误解的 web 开发的基本概念,即数据编码。

据我了解,您不能将字符串传递&nbsp;到后端,因为它被解析为对象,所以我假设您使用 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&nbsp;world

// the server understands this
{
  a: 10,
  b: 'hello',
  nbsp: ';world'
}

&创建错误,因为它是一个特殊字符,不会被视为字符串的一部分。即使你找到了不使用的技巧&nbsp,或者用空格替换它,你也会认为你已经解决了问题,但是......几乎所有的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));


推荐阅读