已使用cors依赖仍出现fetch请求失败问题求助
问题:本地运行正常,但浏览器控制台fetch请求localhost:3500失败
本地代码运行正常,但在Chrome控制台执行fetch('http://localhost:3500/')时返回错误,错误详情:
fetch('http://localhost:3500/'); Promise {} VM42:1
GET http://localhost:3500/ net::ERR_FAILED (anonymous) @ VM42:1 VM42:1
Uncaught (in promise) TypeError: Failed to fetch
at :1:1
后端Express代码如下:
const express = require("express") const app = express(); const path = require("path"); const cors = require("cors") const { logger } = require("./myMiddleware/logEvent"); const errorHandler = require("./myMiddleware/errorHandler"); const PORT = process.env.PORT || 3500; //custom middleware app.use(logger); app.use(cors()); app.use(express.urlencoded({extended: false})); app.use(express.json()); app.use(express.static(path.join(__dirname, "/public"))); app.use('/subdir', require('./routes/subdir')) app.use('/', require('./routes/root')); app.all('*', (req, res)=> { // page not found res.status(404) console.log("Thank You") if(req.accepts("html")) { res.sendFile(path.join(__dirname, "views", "404.html")); }else if(req.accepts("json")) { res.sendFile({ error : "404 not found"}); }else { res.type("txt").send("404 not found"); } }); // CUSTOM ERROR HANDLER app.use(errorHandler); app.listen(PORT, ()=> { console.log("Server running on port "+PORT); });
错误截图:
修复方案
1. 修正404处理逻辑的JSON响应错误
在app.all('*')的404处理代码中,当请求接受JSON格式时,错误使用了res.sendFile()方法——该方法仅用于发送本地文件,不能直接传递JSON对象。将其替换为res.json()即可解决核心问题:
app.all('*', (req, res)=> { // page not found res.status(404) console.log("Thank You") if(req.accepts("html")) { res.sendFile(path.join(__dirname, "views", "404.html")); }else if(req.accepts("json")) { // 替换res.sendFile为res.json res.json({ error : "404 not found"}); }else { res.type("txt").send("404 not found"); } });
2. 验证根路由配置
确认./routes/root.js文件中是否正确定义了GET /的路由处理。如果根路由未正确响应,请求会直接进入404逻辑,而之前的JSON响应错误会导致请求失败。
3. 确认服务器运行状态
检查终端输出是否显示Server running on port 3500,且无任何报错信息。若服务器崩溃或未启动,也会触发ERR_FAILED错误。
4. 检查CORS响应头
在浏览器网络面板中查看请求的响应头,确认是否包含Access-Control-Allow-Origin: *。虽然代码中已配置cors(),但依赖未正确安装可能导致CORS配置失效。
内容的提问来源于stack exchange,提问作者22_Aditya Dey
相关产品推荐
相关产品推荐

