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

React.js异常:Fetch API未调用index.html却返回其HTML内容

Why You're Getting index.html Instead of sample.txt in Your React App & How to Fix It

Hey there! Let's break down why your Fetch call is returning index.html instead of the content from sample.txt, and walk through how to fix it.

Cause Analysis

  • SPA Server Routing Fallback: React apps built with tools like Create React App are single-page applications (SPAs). By default, the development server (and most production servers for SPAs) is configured to return index.html for any request that doesn't match an existing static file or frontend route. If your sample.txt isn't in the right location or the server can't find it, it falls back to serving index.html instead.
  • Incorrect File Placement: If you placed sample.txt inside the src folder, Webpack (the bundler used by CRA) doesn't expose it as a publicly accessible static resource. When you try to fetch it, the server can't locate the file and returns index.html as a fallback.

Step-by-Step Fixes

1. Move sample.txt to the Public Folder

React's public directory is the designated place for static resources that need to be accessed directly via URL.

  • Drag your sample.txt file into the public folder at the root of your project.
  • Your project structure should look like this:
    your-project/
    ├── public/
    │   ├── index.html
    │   └── sample.txt  # Now here!
    ├── src/
    │   ├── App.js
    │   └── components/
    │       └── Sample.js
    

2. Update the Fetch Path

Change your fetch URL to use the root path (starting with /) to ensure it points directly to the static file in public:

// App.js
getSample = async (e) => {
  e.preventDefault();
  fetch('/sample.txt') // Added leading slash for root path
    .then((response) => {
      // Add error handling for missing files
      if (!response.ok) {
        throw new Error('Failed to load sample.txt');
      }
      return response.text();
    })
    .then(data => {
      let sampleArray = data.split(/\r?\n/)
      console.log(sampleArray)
    })
    .catch(error => console.error('Error:', error));
}

3. Verify Your sample.txt Content

Make sure your sample.txt has the line breaks you expect to get the desired array:

This is
a sample
file

When you split this with split(/\r?\n/), you'll get exactly ["This is", "a sample", "file"] as expected.

4. Production Deployment Note (If Applicable)

If you're deploying to a production server like Nginx, ensure your server config prioritizes static files before falling back to index.html. Here's a typical Nginx config snippet:

location / {
  try_files $uri $uri/ /index.html;
}

This tells Nginx to first look for the requested static file (like sample.txt), and only return index.html if the file doesn't exist.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:57:34