Express路由调用fs.writeFile致前端页面刷新问题排查
问题:前端Fetch请求Express后端时页面自动刷新
现象描述
点击页面按钮发起Fetch请求后,页面会自动刷新;移除后端中fs.writeFile/writeFileSync这类修改文件系统的函数调用后,页面不再刷新,功能正常。使用readFile/readFileSync不会触发该问题,仅文件写入、删除等修改操作会引发刷新。
代码示例
前端代码(单HTML文件)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Test</title> </head> <body> <button onclick="func()">Press me</button> <div id="output"></div> <script> function func() { const output = document.getElementById("output"); fetch("http://localhost:3000/") .then((res) => res.json()) .then((data) => { output.textContent = data.message; }); } </script> </body> </html>
后端代码(Node.js + Express)
const express = require("express"); const fs = require("fs"); const app = express(); app.get("/", (req, res) => { res.set("Access-Control-Allow-Origin", "*"); // 处理跨域 fs.writeFileSync("hello.txt", "hello world"); // 触发问题的代码 res.json({ message: "Hello World" }); }); app.listen(3000);
原因分析
并非Express或fs函数本身导致页面刷新,而是开发环境中使用的Live Server扩展会监听文件系统变化,当后端通过fs修改(写入/删除)文件时,Live Server检测到文件变动,自动触发了页面刷新。
解决方法
- 方法1:修改Live Server的监听配置,排除被后端修改的文件(比如示例中的
hello.txt)或目录 - 方法2:停止使用Live Server,改用直接打开本地HTML文件的方式测试,或者部署到常规HTTP服务器运行前端页面
内容的提问来源于stack exchange,提问作者Omar Ahmed
相关产品推荐
相关产品推荐

