React.js异常:Fetch API未调用index.html却返回其HTML内容
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.htmlfor any request that doesn't match an existing static file or frontend route. If yoursample.txtisn't in the right location or the server can't find it, it falls back to servingindex.htmlinstead. - Incorrect File Placement: If you placed
sample.txtinside thesrcfolder, 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 returnsindex.htmlas 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.txtfile into thepublicfolder 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

