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

使用Observable Plot绘图时为何出现→字符?

问题原因与解决方案

出现→是因为字符编码不匹配:Observable Plot生成的箭头符号(→)是UTF-8编码,但你的输出没有明确指定UTF-8,浏览器用了错误的编码(比如ISO-8859-1)解析,导致UTF-8字节被错误解码成乱码字符。

修复方法:

  1. 在JSDOM的HTML模板中添加UTF-8编码声明;
  2. 在HTTP响应头里明确指定Content-Type为UTF-8。

修改后的代码:

import http from 'http';
import * as Plot from "@observablehq/plot";
import {JSDOM} from "jsdom";

// 添加<meta charset="UTF-8">到HTML头部
const jsdom = new JSDOM(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div class='container'><figure id='graphic'>
</figure></div></body>
</html>`);

const sales = [
  {units: 10, fruit: "fig"},
  {units: 20, fruit: "date"},
  {units: 40, fruit: "plum"},
  {units: 30, fruit: "plum"}
];

jsdom.window.document.getElementById('graphic')
                     .appendChild(Plot.dot(sales, {x: "units", y: "fruit"})
                     .plot({document: jsdom.window.document}));

http.createServer(function (req, res) {
  // 设置响应头指定UTF-8编码
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  let html = jsdom.serialize();
  res.end(html);
}).listen(8080);

说明:

  • <meta charset="UTF-8">让浏览器解析HTML时优先使用UTF-8;
  • 响应头的Content-Type则从HTTP层面明确编码,双重保障避免乱码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:45:29