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

如何在客户端调用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

  1. Correct Fetch Target: We switched fetch('/') to fetch('/sendform', { method: 'POST' }) to match your server’s endpoint and request method.
  2. Error Handling: Added a check for res.ok and a .catch() block to handle network errors gracefully—this makes debugging way easier if something goes wrong.
  3. HTML Rendering: Added logic to loop through the fetched data array, 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:33:07