Node.js环境下jQuery无法加载TXT/HTML文件问题求助
解决jQuery .load()无法加载静态文件的问题
你的问题核心在于Node.js服务器仅处理了根路径(/)的请求,当jQuery通过.load()请求Text.txt时,服务器没有对应的处理逻辑,会返回错误;另外前端代码里的console.log(status)中的status变量未定义,所以输出为空。
1. 修改服务器代码,支持静态资源请求
当前服务器仅返回ultimate.html,需要添加逻辑处理其他文件的请求,同时根据文件类型设置正确的Content-Type:
const fs = require("fs"); const http = require("http"); const path = require("path"); // 引入path模块处理文件路径 let server = http.createServer((req, res) => { // 处理根路径请求 if (req.url === "/") { fs.readFile("ultimate.html", "utf-8", (error, data) => { if (error) { res.writeHead(404, {"Content-Type": "text/plain; charset=utf-8"}); res.end("文件未找到"); return; } res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"}); res.end(data); }); } else { // 处理其他静态资源请求,比如Text.txt const filePath = path.join(__dirname, req.url.slice(1)); // 去掉url开头的/,拼接当前目录路径 // 根据文件后缀设置Content-Type const ext = path.extname(filePath); let contentType = "text/plain"; if (ext === ".html") contentType = "text/html; charset=utf-8"; else if (ext === ".txt") contentType = "text/plain; charset=utf-8"; fs.readFile(filePath, "utf-8", (error, data) => { if (error) { res.writeHead(404, {"Content-Type": "text/plain; charset=utf-8"}); res.end("资源未找到"); return; } res.writeHead(200, {"Content-Type": contentType}); res.end(data); }); } }); const PORT = 3000; const HOST = "localhost"; server.listen(PORT, HOST, () => { console.log(`Server is up: http://${HOST}:${PORT}`); });
2. 修复前端代码的问题
- 移除未定义的
console.log(status),或者在.load()的回调函数中获取请求状态 - 确保
.load()的路径正确(Text.txt要和App.js在同一目录下)
修改后的ultimate.html:
<html> <head> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ $("#header").html('Did i disappear?'); // 给.load()添加回调函数查看请求状态 $("#header").load("Text.txt", function(response, status, xhr) { console.log(status); // 现在会输出success/error/notmodified等状态 if (status === "error") { console.log("加载失败: " + xhr.status + " " + xhr.statusText); } }); }); </script> </head> <body> <div id="header"></div> </body> </html>
验证步骤
- 确保
Text.txt文件和App.js、ultimate.html在同一目录下,文件内填写测试内容 - 重启Node.js服务器
- 访问
http://localhost:3000,查看页面是否加载Text.txt的内容,同时打开控制台查看请求状态
内容的提问来源于stack exchange,提问作者Damonis
相关产品推荐
相关产品推荐

