代码之家  ›  专栏  ›  技术社区  ›  Utkarsh Bhatt

为什么Express HTTP server要从本地主机下载res.end()

  •  -2
  • Utkarsh Bhatt  · 技术社区  · 8 年前

    我正在跟踪 Nodejs tutorial from MDN 并使用Express创建了一个基本HTTP服务器。

    通常,当我导航到 http://127.0.0.1:8000 ,网页应显示“Hello World”。但是,使用此代码,一个包含 res.end() 方法在我的电脑上下载。

    这个 hellonode.js 文件:

    const http = require('http');
    
    const PORT = 8000;
    
    http.createServer((req, res) => {
        res.writeHead(200, {
            'Content-Type': 'plain/text'
        });
    
        res.end('Hello World\n');
    }).listen(PORT);
    
    console.log(`Server running at http://127.0.0.1:${PORT}/`);
    

    我正在使用命令运行代码 nodemon hellonode.js . 为什么会这样?

    1 回复  |  直到 8 年前
        1
  •  2
  •   IlIIlllIIIlIIlllIlIllIIIlIlI    8 年前

    这个 Content-Type 是什么决定了浏览器的行为。当 内容类型 比赛 text/plain ,您的浏览器将按预期在窗口中显示文本。

    但是,您当前正在设置 内容类型 像 plain/text ,浏览器无法识别。由于浏览器没有此无法识别类型的响应的默认行为,因此它将响应下载为文件。