簡體   English   中英

TypeError:無法將對象轉換為原始值

[英]TypeError: Cannot convert object to primitive value

我有一個texteditor(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轉換為(string)以避免此錯誤?

我知道您已經解決了該問題,但是您可能會對閱讀本文檔感興趣,因為您的問題是由於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)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM