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

Spring Boot应用中使用JavaScript获取URL请求返回结果报错求助

Fixing Your JavaScript Fetch Request for the /linguagens Endpoint

Hey there! Let's get your JavaScript request working with that Spring Boot controller you've got. First off, your Controller code looks solid—it's set up to return a JSON object with a linguagem key pointing to your Linguagem instance. Now, let's fill in the missing JavaScript part and fix any common issues you might be hitting.

Step 1: Complete JavaScript Code Using Fetch API

Here's a working example that will fetch the data from your /linguagens endpoint and display it when the button is clicked:

// Wait for the DOM to fully load before accessing elements
document.addEventListener('DOMContentLoaded', function() {
  // Grab references to the button and output div
  const verBtn = document.getElementById('verLinguagens');
  const linguagensDiv = document.getElementById('linguagens');

  // Add click event listener to the button
  verBtn.addEventListener('click', async function() {
    try {
      // Fetch data from your backend endpoint
      const response = await fetch('/linguagens');
      
      // Check if the request was successful (HTTP status 200-299)
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      
      // Parse the JSON response into a JavaScript object
      const data = await response.json();
      
      // Extract the linguagem object from the response
      const linguagem = data.linguagem;
      
      // Render the data into the div
      linguagensDiv.innerHTML = `
        <h3>Linguagem:</h3>
        <p>Nome: ${linguagem.name}</p>
        <p>Ativa: ${linguagem.active ? 'Sim' : 'Não'}</p>
      `;
    } catch (error) {
      // Handle any errors (network issues, HTTP errors, etc.)
      linguagensDiv.innerHTML = `<p>Erro ao carregar linguagens: ${error.message}</p>`;
      console.error('Fetch error:', error);
    }
  });
});

Common Pitfalls to Avoid

  • Forgetting to wait for DOM content: If your script runs before the button/div exist in the DOM, getElementById will return null. Wrapping your code in DOMContentLoaded fixes this.
  • Ignoring HTTP errors: The fetch API only rejects on network failures, not on HTTP errors like 404 or 500. Always check response.ok to handle those cases.
  • CORS issues: If your frontend runs on a different port (e.g., frontend on localhost:3000, backend on localhost:8080), add @CrossOrigin to your Controller method to enable cross-origin requests:
    @GetMapping("/linguagens")
    @ResponseBody
    @CrossOrigin(origins = "http://localhost:3000") // Replace with your frontend URL
    public Map<String, Linguagem> linguagens(){
      // ... your existing code ...
    }
    
  • Missing getters in Linguagem class: Spring needs getters for your class fields (like getName() and getActive()) to serialize the object to JSON correctly. Without them, the response might be missing those properties.

Alternative: Using XMLHttpRequest (Older Browsers)

If you need support for older browsers that don't have fetch, here's an alternative using XMLHttpRequest:

document.addEventListener('DOMContentLoaded', function() {
  const verBtn = document.getElementById('verLinguagens');
  const linguagensDiv = document.getElementById('linguagens');
  
  verBtn.addEventListener('click', function() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/linguagens');
    
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        const data = JSON.parse(xhr.responseText);
        const linguagem = data.linguagem;
        linguagensDiv.innerHTML = `
          <h3>Linguagem:</h3>
          <p>Nome: ${linguagem.name}</p>
          <p>Ativa: ${linguagem.active ? 'Sim' : 'Não'}</p>
        `;
      } else {
        linguagensDiv.innerHTML = `<p>Erro: ${xhr.statusText}</p>`;
      }
    };
    
    xhr.onerror = function() {
      linguagensDiv.innerHTML = `<p>Erro de rede ao tentar acessar o endpoint</p>`;
    };
    
    xhr.send();
  });
});

Give either of these a try, and let me know if you run into specific issues like CORS errors or missing data in the response!

内容的提问来源于stack exchange,提问作者Matheus Alcântara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:37:29