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

如何解决Node.js Pug模板中追加HTML响应内容的布局异常问题?

问题解决方法

1. 修复容器标签类型

原代码中#messages使用的是<p>标签,但<p>无法容纳<ul>、<ol>这类块级元素,浏览器会自动将列表移出<p>外,导致布局错乱。将其改为<div>标签:

.chat-messages.has-text-left
  div#messages

2. 优化Showdown转换配置

初始化Converter时添加配置项,确保生成的HTML结构更规范,避免布局异常:

var converter = new showdown.Converter({
  smoothLivePreview: true,
  simpleLineBreaks: true,
  disableForced4SpacesIndentedSublists: false
});

3. 修正Fetch请求的FormData问题

原代码中body: form未定义,需正确获取表单数据:

const form = new FormData(document.querySelector("#chatForm"));
const response = await fetch('/api', {
  method: 'POST',
  body: form
});

4. 添加容器滚动样式

给.chat-messages添加样式,避免内容溢出容器:

.chat-messages {
  max-height: 400px;
  overflow-y: auto;
  padding: 1rem;
}

修正后的完整Pug代码

extends layout
block append head
  script(src='https://cdnjs.cloudflare.com/ajax/libs/showdown/2.1.0/showdown.min.js')
  style.
    .chat-messages {
      max-height: 400px;
      overflow-y: auto;
      padding: 1rem;
    }
block layout-content
  h1.title Welcome to #{title}
  section.section.chat-container
    .container
      .columns
        .box.column.is-full
          .chat-messages.has-text-left
            div#messages
          form#chatForm(action='/api', method='post', enctype="multipart/form-data")
            .field.has-addons
              p.control.is-expanded
                input(class='input', id='query', type='text', placeholder='How can I help?', onkeyup="stoppedTyping()")
              p.control
                input(class='button is-success', id="submit", type='submit', value='Submit', disabled)
      script.
        document.querySelector("#chatForm").addEventListener("submit", async (e) => {
          e.preventDefault();
          const query = document.querySelector("#query").value;
          if (query.trim()) {
            const form = new FormData(document.querySelector("#chatForm"));
            const response = await fetch('/api', {
              method: 'POST',
              body: form
            });
            const data = await response.json();
            var converter = new showdown.Converter({
              smoothLivePreview: true,
              simpleLineBreaks: true
            });
            document.querySelector("#messages").innerHTML += `<p><strong>Query:</strong> ${query}</p>`;
            document.querySelector("#messages").innerHTML += `<p><strong>Response:</strong></p>${converter.makeHtml(data.message)}<br>`;
          } else {
            console.error(`Invalid query!`);
          }
        });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 13:35:07