非同步驗證

這個範例展示如何為 htmx 實作非同步驗證令牌流程。

我們這裡使用的技術將會利用您可以使用 htmx:confirm 事件延遲請求的事實。

首先,我們有一個按鈕,在取得驗證令牌之前不應該發出請求

  <button hx-post="/example" hx-target="next output">
    An htmx-Powered button
  </button>
  <output>
    --
  </output>

接下來,我們將添加一些腳本以使用 auth promise(由函式庫返回)

<script>
  // auth is a promise returned by our authentication system

  // await the auth token and store it somewhere
  let authToken = null;
  auth.then((token) => {
    authToken = token
  })
  
  // gate htmx requests on the auth token
  htmx.on("htmx:confirm", (e)=> {
    // if there is no auth token
    if(authToken == null) {
      // stop the regular request from being issued
      e.preventDefault() 
      // only issue it once the auth promise has resolved
      auth.then(() => e.detail.issueRequest()) 
    }
  })

  // add the auth token to the request as a header
  htmx.on("htmx:configRequest", (e)=> {
    e.detail.headers["AUTH"] = authToken
  })
</script>

這裡我們使用一個全域變數,但您可以使用 localStorage 或任何您偏好的機制,將驗證令牌傳遞給 htmx:configRequest 事件。

完成此程式碼後,htmx 將不會發出請求,直到 auth promise 被解析。