使用节点 Fetch 在 JSON API 响应中正确显示特殊字符
Correctly display special characters in JSON API response using nodeFetch
我有一个通过 HTTP 与 RESTful API 通信的 React 应用程序。
API returns 可能包含特殊字符的 JSON 响应正文。
示例响应可能如下所示:
{
"name": "Property One",
"description": "Res Thick Film 0805 49.9 Ohm 1% 0.25W(1/4W) ±100ppm/°C Pad SMD Automotive T/R",
...
}
问题中的特殊字符为(但不限于)± 和 °。
我使用 nodeFetch
执行请求,如下所示:
nodeFetch(url, { method: 'GET', headers }).then(response => response.json());
如果我在使用 response.json()
反序列化后观察对象,description
属性 现在看起来像这样:
"Res Thick Film 0805 49.9 Ohm 1% 0.25W(1/4W) �100ppm/�C Pad SMD Automotive T/R"
如何阻止特殊字符被替换为 �?
你也可以看看这个问题,也许cskau-g转帖应该对你有帮助
https://github.com/dart-lang/http/issues/175
我认为问题出在编码为 utf-8 且内容类型必须设置为 text/html
您可能应该将 header: Content-Type
设置为 text/html; charset=utf8
。 nodeFetch
支持 UTF-8
开箱即用
我有一个通过 HTTP 与 RESTful API 通信的 React 应用程序。 API returns 可能包含特殊字符的 JSON 响应正文。
示例响应可能如下所示:
{
"name": "Property One",
"description": "Res Thick Film 0805 49.9 Ohm 1% 0.25W(1/4W) ±100ppm/°C Pad SMD Automotive T/R",
...
}
问题中的特殊字符为(但不限于)± 和 °。
我使用 nodeFetch
执行请求,如下所示:
nodeFetch(url, { method: 'GET', headers }).then(response => response.json());
如果我在使用 response.json()
反序列化后观察对象,description
属性 现在看起来像这样:
"Res Thick Film 0805 49.9 Ohm 1% 0.25W(1/4W) �100ppm/�C Pad SMD Automotive T/R"
如何阻止特殊字符被替换为 �?
你也可以看看这个问题,也许cskau-g转帖应该对你有帮助 https://github.com/dart-lang/http/issues/175
我认为问题出在编码为 utf-8 且内容类型必须设置为 text/html
您可能应该将 header: Content-Type
设置为 text/html; charset=utf8
。 nodeFetch
支持 UTF-8
开箱即用