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

Node.js+REST API场景下fetch方法无法获取数据求助

Hey there! Let's break down your issues one by one and fix them step by step.

Issue 1: Server doesn't log any output when accessing minuk_test.html

The core problem here is that your frontend code never actually triggers the API call, and there are a few mistakes in how you're setting up the frontend:

1.1 Wrong way to reference JavaScript in HTML

You used a <link> tag to load your JS file — that's for CSS stylesheets, not JavaScript. You need to use a <script> tag instead. Also, browsers require type="module" if you're using ES module syntax like import, though you don't even need node-fetch in the browser (it has a native fetch API built-in).

1.2 Missing static file hosting in your Node server

Your server isn't set up to serve static files like HTML, JS, or CSS. Without this, the browser can't load your JS file at all.

Fixed Code

Updated minuk_test.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API TEST</title>
    <!-- Use script tag for JS, relative path if JS is in the same folder as HTML -->
    <script src="./minuks_test.js"></script>
</head>
<body>
    <h1>Test</h1>
    <div id="restaurant">
        <span></span>
        <span></span>
    </div>
</body>
</html>

Add static file hosting to your Node server:

const express = require('express');
const mysql = require('mysql');
const fs = require('fs');
var app=express();

// Add this line to serve static files from your Project folder
app.use(express.static('Project'));

app.listen(9999,function(){ 
    console.log('Server is running on port 9999');
})

// Don't forget to specify your database name in the MySQL connection
var client=mysql.createConnection({
    user:'root',
    password:'pswd',
    database: 'your_restaurant_db_name' // Replace with your actual DB name
});

Now you can access your HTML at localhost:9999/html/minuk_test.html, and the server will serve both the HTML and JS files correctly.

Issue 2: data is undefined when running the JS file standalone

Two key mistakes here:

  1. You forgot to return response.json() from the first .then() — this means the second .then() doesn't receive any data.
  2. You had a syntax error: data={ should be data=>.
  3. For Node.js, make sure you've installed node-fetch (npm install node-fetch) and configured your module system correctly.

Fixed standalone JS file (ES Module):

If your package.json has "type": "module":

import fetch from "node-fetch";
function getAPI(){
    const url=`http://127.0.0.1:9999/store/restaurant_info`;
    fetch(url)
    .then(response=>{
        console.log(response);
        // Return the json promise so the next then can use it
        return response.json();
    })
    .then(data=>{
        console.log(data);
    })
    // Add error handling to catch any network/API issues
    .catch(err => {
        console.error('Request failed:', err);
    });
}
getAPI();

Fixed standalone JS file (CommonJS):

If you're not using ES modules:

const fetch = require('node-fetch');
function getAPI(){
    const url=`http://127.0.0.1:9999/store/restaurant_info`;
    fetch(url)
    .then(response=>{
        console.log(response);
        return response.json();
    })
    .then(data=>{
        console.log(data);
    })
    .catch(err => {
        console.error('Request failed:', err);
    });
}
getAPI();

Extra Tips

  • Always check your browser's DevTools (F12) → Console tab for frontend errors, and Network tab to see if your fetch request is actually being sent.
  • Make sure your MySQL connection is successful — add a check like client.connect(err => { if(err) console.log(err); }) to catch DB connection issues.
  • Your original API route for HTML uses fs.readFile, but with static file hosting, you don't need this route anymore — the express.static middleware will handle serving HTML files automatically.

内容的提问来源于stack exchange,提问作者정민욱

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 23:04:08