You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js服务器重定向时出现ERR_HTTP_HEADERS_SENT错误求助

问题分析与解决方案

错误原因

  1. 重复发送HTTP头部:在/msg的POST请求处理分支中,你先调用了res.write()输出HTML内容,此时Node.js会自动发送默认的200状态码和Content-Type头部。后续又调用res.writeHead(302)设置重定向头部,这就触发了ERR_HTTP_HEADERS_SENT错误——HTTP响应头部只能发送一次。
  2. 异步逻辑顺序错误:req.on("end")是异步触发的,原代码在绑定该事件后直接调用res.end(),会导致响应提前结束,不仅逻辑顺序混乱,还和重定向操作冲突。

修复后的代码

import http from "http";
import fs from "fs";
import path from "path";

export default sample_server()

function sample_server() {
    // 确保files目录存在,避免写入文件时报错
    const filesDir = path.resolve("./files");
    if (!fs.existsSync(filesDir)) {
        fs.mkdirSync(filesDir);
    }

    const server = http.createServer((req, res) => {
        const { url, method } = req;
        
        if (url === "/home") {
            res.setHeader("Content-Type", "text/html");
            res.write("<html>");
            res.write("<head><title>page</title></head>");
            res.write("<body><center><h1>welcome</h1>");
            res.write("<form method='POST' action='/msg'>");
            res.write("<input type='text' name='msg'>");
            res.write("<input type='submit'>");
            res.write("</form></center></body></html>");
            return res.end();
        } else if (url === "/msg" && method === "POST") {
            let msgChunks = [];
            req.on("data", chunk => {
                msgChunks.push(chunk);
            });
            req.on("end", () => {
                try {
                    // 解析并解码POST数据(处理URL编码的特殊字符)
                    const rawMsg = Buffer.concat(msgChunks).toString().split("=")[1];
                    const decodedMsg = decodeURIComponent(rawMsg.replace(/\+/g, " "));
                    // 写入文件后再发送重定向响应
                    fs.appendFileSync("./files/entry.txt", `entered: ${decodedMsg}\n`);
                    res.writeHead(302, { Location: "/home" });
                    res.end();
                } catch (err) {
                    // 捕获错误,避免服务器崩溃
                    res.writeHead(500, { "Content-Type": "text/html" });
                    res.write("<html><body><center><h1>Server Error</h1></center></body></html>");
                    res.end();
                }
            });
        } else {
            res.writeHead(404, { "Content-Type": "text/html" });
            res.write("<html>");
            res.write("<head><title>page</title></head>");
            res.write("<body><center><h1>not found</h1></center></body>");
            res.write("</html>");
            return res.end();
        }
    });
    server.listen(3030);
}

关键修复点

  • 移除/msg分支中多余的res.write()操作,避免提前发送响应头部。
  • 将重定向逻辑移到req.on("end")回调内部,确保在接收完POST数据并写入文件后,再发送重定向响应。
  • 新增files目录的检查与创建,解决目录不存在导致的写入失败问题。
  • 添加POST数据的解码处理,修复URL编码带来的字符异常(比如空格变为+)。
  • 增加错误捕获,避免服务器因文件写入失败而崩溃。

内容的提问来源于stack exchange,提问作者ilia0017

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:50:31