Spring Boot应用中使用JavaScript获取URL请求返回结果报错求助
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,
getElementByIdwill returnnull. Wrapping your code inDOMContentLoadedfixes this. - Ignoring HTTP errors: The
fetchAPI only rejects on network failures, not on HTTP errors like 404 or 500. Always checkresponse.okto handle those cases. - CORS issues: If your frontend runs on a different port (e.g., frontend on
localhost:3000, backend onlocalhost:8080), add@CrossOriginto 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()andgetActive()) 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

