如何在客户端调用Fetch方法接收服务器端返回的数组?
How to Fetch and Display a Server-returned Array with Client-side Fetch
Hey there! Let's get your client-side code working properly to fetch that array from your server and render it in index.html. Here's what's off in your current code, plus the fixed version:
First, Let's Spot the Issues
- Your server exposes a POST endpoint at
/sendform, but your client is fetching from the root path (/) with the default GET method—this won’t hit the right endpoint at all. - You haven’t added logic to actually inject the fetched array data into your HTML.
Fixed Client-side Code (client.js)
function tableContent() { // Target the correct POST endpoint and specify the request method fetch('/sendform', { method: 'POST' }) .then(res => { console.log('Response status:', res); if (!res.ok) { throw new Error('Network response was not ok'); } return res.json(); // Parse the server's array response into a JavaScript object }) .then(data => { // Grab a container element from your index.html (add this element first!) const container = document.getElementById('array-container'); // Clear any existing content in the container container.innerHTML = ''; // Loop through the fetched array and render each item data.forEach(item => { // Create a new element for each object in the array const itemElement = document.createElement('div'); // Format the key-value pairs from the object (e.g., "h: 1" or "e: 2") const entryText = Object.entries(item).map(([key, value]) => `${key}: ${value}`).join(', '); itemElement.textContent = entryText; // Add the element to the page container container.appendChild(itemElement); }); }) .catch(error => { // Handle any errors (network issues, invalid responses, etc.) console.error('There was a problem with the fetch operation:', error); }); } // Don't forget to call the function to trigger the fetch! tableContent();
Required Update to index.html
Add a container where the array content will be displayed (place this wherever you want the data to show up):
<div id="array-container"></div>
Breakdown of Key Changes
- Correct Fetch Target: We switched
fetch('/')tofetch('/sendform', { method: 'POST' })to match your server’s endpoint and request method. - Error Handling: Added a check for
res.okand a.catch()block to handle network errors gracefully—this makes debugging way easier if something goes wrong. - HTML Rendering: Added logic to loop through the fetched
dataarray, create DOM elements for each item, and append them to a container in your HTML.
Quick Server-side Note
Your existing server code works fine for this example, but if you ever need to process incoming data from the client (like form submissions), you’ll want to add middleware like express.json() or express.urlencoded() to parse the request body.
内容的提问来源于stack exchange,提问作者ali
相关产品推荐
相关产品推荐

