In website operation, captcha plays a crucial role, it can effectively resist spam and malicious attacks, and also ensure normal interaction between users and the website.For a content management system like AnQiCMS (AnQiCMS) that pursues efficiency and stability, the reliability of the captcha directly affects user experience and website security.However, sometimes we may encounter the problem that the captcha image does not display correctly after refreshing, which not only confuses the user but may also hinder the normal business process.

As an experienced website operations expert, I will explain in detail how to ensure that the AnQiCMS captcha image is displayed stably and correctly every time it is refreshed.

Understand the principle of AnQiCMS captcha operation

AnQiCMS is a system developed based on the Go language, which usually adopts the way of generating pictures on the server side when dealing with captcha, and the front end gets and updates them through asynchronous requests (AJAX). When the user visits a page containing captcha, the front end will initiate a special API request to the AnQiCMS backend (usually/api/captcha)。After receiving the request, the backend will generate a verification code image containing random characters and return it along with a unique verification code ID to the frontend.srcAttribute, while updating a hidden field.captcha_idIn fact, every time the captcha is refreshed, it is actually a new request to the server and dynamic updating of the image and corresponding verification information.

Implement front-end code: ensure the key to dynamic updates

The AnQiCMS captcha is usually applied to comment forms or comment areas. It is crucial to ensure that the captcha image can be displayed and refreshed correctly, as the implementation of the front-end code is essential. The following istag-/anqiapi-other/167.htmlThe recommended implementation in the document, let us decompose its key points one by one:

Firstly, in your form, you will need the following HTML elements: a hidden input box to storecaptcha_id, a text input box for user input of the captcha, and one<img>The label is used to display the captcha image.

<div style="display: flex; clear: both">
  <input type="hidden" name="captcha_id" id="captcha_id">
  <input type="text" name="captcha" required placeholder="请填写验证码" class="layui-input" style="flex: 1">
  <img src="" id="get-captcha" style="width: 150px;height: 56px;cursor: pointer;" />
  <script>
    document.getElementById('get-captcha').addEventListener("click", function (e) {
      fetch('/api/captcha')
              .then(response => {
                // 确保响应是JSON格式,并解析
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
              })
              .then(res => {
                // 成功获取验证码数据后,更新页面元素
                document.getElementById('captcha_id').setAttribute("value", res.data.captcha_id);
                document.getElementById('get-captcha').setAttribute("src", res.data.captcha);
              })
              .catch(err => {
                // 捕获并处理错误,例如网络问题或API返回非预期数据
                console.error("Failed to fetch captcha:", err);
                // 可以在这里添加用户友好的错误提示
                alert("验证码加载失败,请稍后再试或检查网络。");
              });
    });
    // 页面加载完成后,立即触发一次点击事件,以显示初始验证码
    document.getElementById('get-captcha').click();
  </script>
</div>

The core of this code lies in the JavaScript part:

  1. Event listening: It is for the captcha<img>Label (ID isget-captchaAdded a click event listener. The event will be triggered when the user clicks on the captcha image.
  2. Asynchronous request:fetch('/api/captcha')It will send an asynchronous request to the AnQiCMS backend to get a new captcha.
  3. Data update: After the request is successful, the backend will return a JSON object containingcaptcha_idand a new captcha unique identifiercaptcha(New captcha image URL). The front end passes throughsetAttributeMethod, assign these new values to the hiddencaptcha_idinput boxes and<img>label'ssrcProperty.
  4. initial loading:document.getElementById('get-captcha').click();This line ensures that the captcha image is displayed immediately after the page is loaded, without the need for the user to click manually.

If you are using jQuery, you can also use the following simplified syntax:

<script>
  $('#get-captcha').on("click", function (e) {
    $.get('/api/captcha', function(res) {
      if (res.code === 0 && res.data) { // 假设成功返回code为0,并且data存在
        $('#captcha_id').attr("value", res.data.captcha_id);
        $('#get-captcha').attr("src", res.data.captcha);
      } else {
        console.error("Failed to fetch captcha:", res.msg || "未知错误");
        alert("验证码加载失败,请稍后再试。");
      }
    }, 'json')
    .fail(function(jqXHR, textStatus, errorThrown) {
        console.error("AJAX error fetching captcha:", textStatus, errorThrown);
        alert("验证码加载失败,请检查网络连接。");
    });
  });
  $('#get-captcha').click(); // 页面加载后立即显示初始验证码
</script>

Common display issues and troubleshooting strategies

Even with correct code, captcha images may sometimes still have issues. Here are some common problems and their troubleshooting approaches:

  1. The image does not display or displays an old image (no change)

    • Browser Cache IssueThe user's browser may cache old images.Try to make the user refresh hard (Ctrl+F5 or Shift+F5) or clear the browser cache.For developers, the browser cache should be disabled during the development phase.
    • Front-endsrcNot Updated: Check with the browser developer tools (F12)<img>label'ssrcWhether the property has indeed changed after clicking refresh. IfsrcThe value does not change, indicating that the JavaScript code was not executed correctly or the DOM was not updated. Check the console for any JavaScript errors.
    • captcha_idNot Updated: The captcha image and its correspondingcaptcha_idmust be synchronized updates. Ifcaptcha_idit is not updated correctly, even though the image seems to be refreshed, the backend may still fail to update when the form is submitted.captcha_idAn error occurred due to mismatch. Please check the hidden input box.valueWhether it updates with the image.
  2. Network request failed (captcha loading failed).

    • /api/captchaPath issue.Ensure that your website's root path is correctly configured and that the reverse proxy rules (refer to) of the server (such as Nginx or Apache) can correctly direct toapache.md/docker-1panel.mdthe relevant documents)/api/captchaThe request is forwarded to the AnQiCMS backend service. If the reverse proxy configuration is incorrect, the request may not reach AnQiCMS.
    • Server-side errorCheck the backend logs of AnQiCMS. AnQiCMS is developed based on Go language, with good performance and stability, but configuration errors or database connection issues can still lead to/api/captchaRequest failed. Detailed error information is usually provided in the log.
    • Firewall or CDN: Whether the website firewall (WAF) or CDN service is affecting/api/captchaDoes this API path have limitations or restrictions? This may cause the request to return abnormally.
    • HTTP/HTTPS mixed contentIf your website has enabled HTTPS, but the captcha image URL (res.data.captchaIt is an HTTP protocol, the browser may treat it as 'mixed content' and block loading, causing the image not to display. Ensure that all resources are loaded through HTTPS.
  3. Image is damaged or displays an error (such as showing an X or garbage code)

    • Image generation failedAlthough AnQiCMS's Go backend is highly stable, in rare cases, issues such as missing font libraries, problems with the image generation library, or backend logic errors may cause the generated image data to be corrupted.This requires further checking of the server logs or contacting AnQiCMS technical support.
    • Image path is inaccessible:res.data.captchaCan the returned image URL be accessed directly in the browser? If not, there may be issues with file permissions, storage configuration, or the image service itself.
    • Response header issue: Make sure/api/captchaHeader of returned imageContent-TypeSet correctlyimage/pngOr other image types.

**Practice

  • Enable backend captcha function
  • Use the browser developer tools: Proficiently using the F12 developer tools is a powerful tool for troubleshooting. Monitor through the "Network" tab/api/captchaCheck the status code and response content, for any red error requests.Check the "Console" tab for any JavaScript errors.
  • Place the code locationPlace the front-end code related to the captcha accurately near the form HTML structure where the captcha is required for easy management and debugging.
  • **Friendly error messages**