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

使用qrcode库生成二维码部分场景无法正常显示求助

问题排查与解决方案

问题原因

  • 前端API错误篡改二维码数据:在UsersHttp.postNewRestaurantQRCode方法中,你错误地在传入的qrCode后拼接了无关字符串"asf",直接破坏了二维码生成的Base64格式数据URL(Base64字符串有严格的格式规范,额外字符会导致解析失败)。这是导致多数场景下二维码无法加载的核心原因——本质上所有存储的二维码数据都是无效的,仅部分输入场景下浏览器偶然勉强解析。
  • 缺乏错误捕获机制:QRcode.toDataURL可能因输入内容问题抛出异常,但代码未捕获错误,无法及时定位生成过程中的问题。
  • 后端全局变量存储风险:使用全局变量let qr存储二维码数据,多请求并发时会互相覆盖,导致获取到的二维码并非预期内容。

解决方案

1. 修复前端API的错误拼接

修改UsersHttp.postNewRestaurantQRCode方法,移除多余的字符串拼接,同时添加await确保请求完成:

import axios from "axios";

const baseBackendURL = `http://localhost:5006/users/`;
export class UsersHttp{

    static async postNewRestaurantQRCode(qrCode: string) {
        // 移除+"asf",并添加await确保请求执行完成
        await axios({
            method: 'put',
            url: baseBackendURL + "arad11",
            data: {
                img: qrCode
            }
        })
    }

    static async getQR(){
        return await axios({
            url: baseBackendURL,
            method: 'get',
        });
    }
}

2. 添加二维码生成的错误捕获

修改qrGenerator函数,捕获生成过程中的异常,便于调试和提示用户:

const qrGenerator = useCallback(() => {
    QRcode.toDataURL(`https://github.com/${username}`)
        .then(setSrc)
        .catch(err => {
            console.error('二维码生成失败:', err);
            alert('二维码生成失败,请检查输入内容');
        });
},[username]);

3. 后端改用实例变量存储

替换全局变量为控制器实例变量,避免并发请求互相覆盖:

import { Body, Controller, Get, Param, Put } from '@nestjs/common';
import { AppService } from './app.service';

@Controller("/users")
export class AppController {
  private qr: string; // 使用实例变量替代全局变量
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.qr;
  }

  @Put(":id")
  restaurantQRCdoe(@Param('id') id: string, @Body('img') qrCode: string) {
    this.qr = qrCode;
  }
}

4. 前端增加数据有效性校验

在获取二维码后,校验数据是否为有效的Base64数据URL,避免无效数据渲染:

const getQRFromBackend = useCallback(async () => { 
     const res = (await UsersHttp.getQR()).data;
     // 校验是否为合法的图片data URL
     if (res && res.startsWith('data:image/png;base64,')) {
         setqr(res);
     } else {
         console.error('获取到的二维码数据无效');
         setqr('');
     }
},[]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 07:57:27