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

Node.js新手求助:如何按服务端URL将JSON数据渲染为HTML列表?

Solution for Rendering Greens Kiosk Data into HTML Lists

Hey there! Let's walk through how to get your Node.js backend data displayed in that HTML structure you need. First, let's fix a tiny oversight in your backend code, then build the frontend to fetch and render the data.

Step 1: Fix & Complete the Backend Code

First, notice your /products/vegetables route is missing a res.end() call—this will cause requests to hang indefinitely. Also, your GreensKiosk.js needs to export the getItems function so the server can use it. Let's update both files:

Updated Server.js

var http = require('http'); // Import Node.js core module
var GreensKiosk = require('./GreensKiosk');
var server = http.createServer(function (req, res) { // create web server
    // Set CORS headers
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Request-Method', '*');
    res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
    res.setHeader('Access-Control-Allow-Headers', '*');
    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }
    if (req.url == '/') { // check the URL of the current request
        // set response header
        res.writeHead(200, { 'Content-Type': 'text/html' });
        // set response content
        res.write('<html><body><p>Greens Kiosk API.</p></body></html>');
        res.end();
    } else if (req.url == "/products") { // check the URL of the current request
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.write(JSON.stringify(GreensKiosk.getItems()));
        res.end();
    } else if (req.url == "/products/fruits") {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.write(JSON.stringify(GreensKiosk.getItems('fruits')));
        res.end();
    } else if (req.url == '/products/vegetables') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.write(JSON.stringify(GreensKiosk.getItems('vegetables')));
        res.end(); // Added this line to finish the request
    }
});
server.listen(3000);

Updated GreensKiosk.js

let products = [
    { name: 'Mangoes', category: 'fruits' },
    { name: 'Apples', category: 'fruits' },
    { name: 'Bananas', category: 'fruits' },
    { name: 'Oranges', category: 'fruits' },
    { name: 'Grapes', category: 'fruits' },
    { name: 'Kales', category: 'vegetables' },
    { name: 'Onions', category: 'vegetables' },
    { name: 'Tomatoes', category: 'vegetables' },
    { name: 'Cabbages', category: 'vegetables' }
];

// Export the getItems function for the server to use
module.exports = {
    getItems: function(category) {
        // Filter by category if provided, else return all products
        return category ? products.filter(item => item.category === category) : products;
    }
};

Step 2: Build the Frontend HTML File

Create a new file called index.html in your project folder. This file will fetch data from your API and populate the lists you specified:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greens Kiosk</title>
</head>
<body>
    <h3>Fruits</h3>
    <ul id="fruList"></ul> <!-- Fruits will render here -->
    
    <h3>Vegetables</h3>
    <ul id="vegList"></ul> <!-- Vegetables will render here -->

    <script>
        // Reusable function to fetch data and populate a list
        async function populateList(apiUrl, targetListId) {
            try {
                // Fetch JSON data from your Node.js API
                const response = await fetch(apiUrl);
                const items = await response.json();
                
                // Get the target list element from the DOM
                const listElement = document.getElementById(targetListId);
                
                // Clear any existing content (clean start)
                listElement.innerHTML = '';
                
                // Loop through each item and create a list item
                items.forEach(item => {
                    const listItem = document.createElement('li');
                    listItem.textContent = item.name;
                    listElement.appendChild(listItem);
                });
            } catch (error) {
                console.error('Oops, failed to fetch data:', error);
            }
        }

        // Run the population functions when the page finishes loading
        window.addEventListener('load', () => {
            populateList('http://localhost:3000/products/fruits', 'fruList');
            populateList('http://localhost:3000/products/vegetables', 'vegList');
        });
    </script>
</body>
</html>

How It All Comes Together

  1. Backend: Your server now properly handles all requests and exports the product data via the getItems function.
  2. Frontend: When the HTML page loads, it uses the browser's fetch API to call your Node.js endpoints. The populateList function takes the returned JSON, creates list items for each product, and adds them to the correct <ul> element.

How to Run

  1. Start your Node.js server: Open a terminal, navigate to your project folder, and run node Server.js.
  2. Open index.html in your browser—you’ll see all fruits and vegetables listed under their respective headers!

内容的提问来源于stack exchange,提问作者Nickson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:07:37