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

如何在HTML页面中展示POST请求返回的谷歌身份验证器二维码

谷歌身份验证器二维码响应插入HTML的实现方案

以下是根据接口返回的三种常见数据类型对应的实现方案:


方案1:接口返回图片二进制流(预览可直接看到二维码的常见场景)

  • 实现逻辑:将二进制流转为临时URL,直接赋值给img标签的src属性
  • 代码示例:
// 提前在HTML中准备占位标签:<img id="ga-qrcode" alt="谷歌验证器二维码">
const qrcodeImg = document.getElementById('ga-qrcode')

fetch('你的POST接口地址', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    // 按需补充鉴权token等自定义请求头
  },
  body: JSON.stringify({
    // 补充你的业务请求参数
  }),
  // 跨域请求需带凭证的话开启下面的配置
  // credentials: 'include'
}).then(res => res.blob())
  .then(blob => {
    // 生成临时图片URL
    const qrcodeUrl = URL.createObjectURL(blob)
    qrcodeImg.src = qrcodeUrl
    // 页面卸载时释放临时URL,避免内存泄漏
    window.addEventListener('beforeunload', () => URL.revokeObjectURL(qrcodeUrl))
  })

方案2:接口返回Base64编码的图片字符串

  • 实现逻辑:补全Base64图片前缀后直接赋值给img标签的src属性
  • 代码示例:
const qrcodeImg = document.getElementById('ga-qrcode')

fetch('你的POST接口地址', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({/* 业务请求参数 */})
}).then(res => res.json())
  .then(data => {
    // 假设接口返回的base64内容存在qrcode_base64字段中
    const base64Prefix = 'data:image/png;base64,'
    const qrcodeSrc = data.qrcode_base64.startsWith(base64Prefix) ? data.qrcode_base64 : base64Prefix + data.qrcode_base64
    qrcodeImg.src = qrcodeSrc
  })

方案3:接口返回otpauth格式的绑定链接

  • 实现逻辑:拿到otp绑定链接后,用前端二维码生成库直接渲染二维码
  • 代码示例(使用轻量qrcode生成库):
// 提前在HTML中准备占位标签:<div id="ga-qrcode-container"></div>
const qrcodeContainer = document.getElementById('ga-qrcode-container')

fetch('你的POST接口地址', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({/* 业务请求参数 */})
}).then(res => res.json())
  .then(data => {
    // 假设接口返回的otp链接存在otp_url字段中
    new QRCode(qrcodeContainer, {
      text: data.otp_url,
      width: 200,
      height: 200
    })
  })

注意:如果接口有跨域校验,需要服务端配置允许跨域,避免请求被浏览器拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:06:04