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

如何获取Express.js动态路由传递给React.js前端的数据?

Fixing Express Dynamic Route + React Data Fetching

Got it, let's work through this together. You've got two key issues here: a bug in your Express backend code, and the main problem where your React frontend isn't replacing the dynamic :filename parameter with an actual file name when making the request.

Step 1: Fix the Express Backend First

First, let's clean up your backend route—right now it has a syntax error that's preventing it from sending the JSON data correctly:

router.route("/list/:filename").get((req, res) => { 
  const filePath = `./api/assignment_data/${req.params.filename}.json`;
  
  fs.readFile(filePath, (err, data) => { 
    if (err) { 
      // Don't throw an error (this will crash your server!)
      // Instead, send a proper 404 or error response
      return res.status(404).json({ error: "File not found" });
    }
    // Parse the buffer data into a JSON object
    const fileContent = JSON.parse(data);
    // Send the JSON response
    res.json(fileContent);
    console.log("Data sent successfully");
  });
});

What changed:

  • Used template literals for cleaner file path construction
  • Replaced the invalid foundFile => res.json(foundFile) line (this was an unused arrow function) with actual JSON parsing and response sending
  • Added proper error handling (return a 404 instead of crashing the server if the file doesn't exist)

Step 2: Fix the React Frontend Fetch Request

Your frontend is currently sending a request to the literal URL /list/:filename—Express is looking for a file named :filename.json, which doesn't exist. You need to replace :filename with the actual name of the file you want to fetch.

Example 1: Fetch a specific hardcoded filename

If you know the filename upfront, just replace the parameter directly:

import { useEffect, useState } from 'react';

function MyComponent() {
  const [metrics, setMetrics] = useState(null);

  useEffect(() => {
    // Replace "my-data-file" with your actual filename (without .json)
    const filename = "my-data-file";
    fetch(`/list/${filename}`)
      .then(res => {
        if (!res.ok) {
          throw new Error(`HTTP error! Status: ${res.status}`);
        }
        return res.json();
      })
      .then(jsonRes => setMetrics(jsonRes))
      .catch(err => console.error("Failed to fetch data:", err));
  }, []);

  return (
    <div>
      {metrics ? (
        <pre>{JSON.stringify(metrics, null, 2)}</pre>
      ) : (
        <p>Loading data...</p>
      )}
    </div>
  );
}

export default MyComponent;

Example 2: Fetch based on a dynamic value (e.g., React Router URL parameter)

If your filename comes from the React Router URL (like /dashboard/:filename), use useParams to get it:

import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

function Dashboard() {
  const [metrics, setMetrics] = useState(null);
  const { filename } = useParams(); // Get filename from React Router URL

  useEffect(() => {
    if (!filename) return; // Don't fetch if filename is missing

    fetch(`/list/${filename}`)
      .then(res => {
        if (!res.ok) {
          throw new Error(`HTTP error! Status: ${res.status}`);
        }
        return res.json();
      })
      .then(jsonRes => setMetrics(jsonRes))
      .catch(err => console.error("Failed to fetch data:", err));
  }, [filename]); // Re-run effect when filename changes

  return (
    <div>
      {metrics ? (
        <pre>{JSON.stringify(metrics, null, 2)}</pre>
      ) : (
        <p>Loading data for {filename}...</p>
      )}
    </div>
  );
}

export default Dashboard;

Key Fixes in Frontend:

  • Used template literals (`...`) to inject the actual filename variable into the fetch URL
  • Added error handling with .catch() to catch network errors or HTTP errors
  • Added a dependency array to useEffect so the fetch runs only when the filename changes (prevents unnecessary requests)

Final Notes

  • Make sure your Express server is configured to serve your React app correctly (if they're running on the same port, or you've set up proxy in React's package.json)
  • Double-check that the file path in Express is correct relative to where your server is running (use path.resolve if you want an absolute path to avoid confusion)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:12:44