React项目localhost 404问题求助:无法加载App.js资源
本地环境资源加载404及无法查看App.js代码问题
我在localhost环境下遇到两个问题:
- 无法查看App.js文件的代码
- 出现资源加载错误:
Failed to load resource: the server responded with a status of 404 (Not Found)
App.js 代码
import React, { useState } from 'react'; import './App.css'; function App() { const [message, setMessage] = useState(''); const [response, setResponse] = useState(''); const handleSubmit = (e) => { e.preventDefault(); fetch('http://localhost:3001', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message }) }) .then(res => res.json()) .then(data => setResponse(data.message)); } return ( <div className="App"> <form onSubmit={handleSubmit}> <textarea value={message} onChange={e => setMessage(e.target.value)} ></textarea> <button type="submit">Submit</button> </form> <div>{response}</div> </div> ); } export default App
后端index.js代码
const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const app = express(); const port = 3001; app.use(bodyParser.json()); app.use(cors()); app.post('/', (req, res) => { res.json({ message: 'Hello World!' }) }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
项目依赖
── @testing-library/jest-dom@5.16.5 ├── @testing-library/react@13.4.0 ├── @testing-library/user-event@13.5.0 ├── cors@2.8.5 ├── express@4.18.2 ├── react-dom@18.2.0 ├── react-scripts@5.0.1 ├── react@18.2.0 └── web-vitals@2.1.4
可能的问题及解决建议
1. 资源加载404的修复方案
- 确认前端服务状态:React项目默认启动在3000端口,执行
npm start启动服务,确保访问地址为http://localhost:3000,若修改过端口则对应调整。 - 检查文件路径:App.js必须放在
src/目录下(符合create-react-app规范),同时确认前端根目录的index.js正确导入了App.js。 - 启动后端服务:执行
node index.js启动后端,控制台出现Example app listening at http://localhost:3001才算正常运行,否则前端请求会返回404。
2. 无法查看App.js代码的修复方案
- 检查source map配置:查看项目根目录的
.env文件,若存在GENERATE_SOURCEMAP=false则删除,react-scripts默认开启source map生成,关闭后浏览器无法解析原代码。 - 清除浏览器缓存:按
Ctrl+Shift+R(Windows)或Cmd+Shift+R(Mac)强制刷新页面,清除旧缓存文件。 - 重新安装依赖:删除
node_modules和package-lock.json,执行npm install重新安装依赖,再重启开发服务,避免打包异常导致source map生成失败。
内容的提问来源于stack exchange,提问作者OGshar
相关产品推荐
相关产品推荐

