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

基于HX-Trigger响应头触发表格GET请求失效问题求助

解决HX-Trigger响应头无法触发表格GET请求的问题

问题场景

我通过响应头中的HX-Trigger尝试触发页面上表格tbody的GET请求,后端已经正确返回HX-Trigger: todoAdded响应头,但表格的hx-get请求始终未触发;当把hx-trigger的值替换为load时,请求能正常执行。

相关代码如下:

HTML代码

<table class="table">
  <thead>
    <tr>
      <th>Tasks</th>
      <th>Date</th>
      <th>Complete</th>
      <th></th>
    </tr>
  </thead>
  <tbody id="todo-table" hx-get="http://localhost:8081/data" hx-trigger="todoAdded from:body">
  </tbody>
</table>

Go后端代码

func SubmitTodo(w http.ResponseWriter, r *http.Request) {
    http.Header.Add(w.Header(), "Access-Control-Allow-Methods", "*")
    http.Header.Add(w.Header(), "Access-Control-Allow-Origin", "*")
    http.Header.Add(w.Header(), "Access-Control-Allow-Headers", "*")

    // Stop here if its Preflighted OPTIONS request
    if r.Method == "OPTIONS" {
        return
    }

    // Get the value from the form field
    value := r.FormValue("todo")
    if value == "" {
        return
    }

    todoList = append(todoList, todoTask{Task: value, Done: false, InputtedDate: time.Now()})
    fmt.Println(value)

    w.Header().Set("HX-Trigger", "todoAdded")

    // Respond with an "ok" message and set the HX-Trigger header
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("ok"))
}

问题原因

核心问题是跨域请求下,浏览器默认不会暴露自定义响应头HX-Trigger给前端,导致Htmx无法读取到这个响应头,自然无法触发对应的todoAdded事件。

解决方案

在后端的CORS配置中添加Access-Control-Expose-Headers头,显式将HX-Trigger暴露给前端:

修改Go后端的CORS头部配置部分,新增一行:

http.Header.Add(w.Header(), "Access-Control-Expose-Headers", "HX-Trigger")

完整修改后的后端代码片段:

func SubmitTodo(w http.ResponseWriter, r *http.Request) {
    http.Header.Add(w.Header(), "Access-Control-Allow-Methods", "*")
    http.Header.Add(w.Header(), "Access-Control-Allow-Origin", "*")
    http.Header.Add(w.Header(), "Access-Control-Allow-Headers", "*")
    // 新增:暴露HX-Trigger响应头给前端
    http.Header.Add(w.Header(), "Access-Control-Expose-Headers", "HX-Trigger")

    // Stop here if its Preflighted OPTIONS request
    if r.Method == "OPTIONS" {
        return
    }

    // ... 其余代码保持不变
}

验证

修改完成后,重新启动后端:

  1. 在浏览器开发者工具的网络面板中,查看提交todo的请求响应头,确认存在Access-Control-Expose-Headers: HX-Trigger;
  2. 再次提交todo,表格的hx-get请求会被正常触发,更新表格内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:42:46