Node.js服务器"404 not found"消息到404.html页面

 囡囡需要嗳 发布于 2023-02-06 14:34

我正在使用node.js,我想知道如何显示404.html而不是"404 Not Found"消息.

这是我的server.js:

var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;

http.createServer(function(request, response) {

var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);

path.exists(filename, function(exists) {
if(!exists) {
  response.writeHead(404, {"Content-Type": "text/plain"});
  response.write("404 Not Found\n");
  response.end();
  return;
}

if (fs.statSync(filename).isDirectory()) filename += 'public/Index/index.html';

fs.readFile(filename, "binary", function(err, file) {
  if(err) {        
    response.writeHead(500, {"Content-Type": "text/plain"});
    response.write(err + "\n");
    response.end();
    return;
  }

  response.writeHead(200);
  response.write(file, "binary");
  response.end();
  });
 });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

因为你可以看到它只是一个静态文件服务器,我没有使用express.js或任何东西.

1 个回答
  • 我,

    在你的404案件中

      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
    

    你可以改为

      response.writeHead(404, {"Content-Type": "text/html"});
      response.write(HTMLDATA);
      response.end();
    

    'HTMLDATA'是HTML字符串或对您收集的文件的引用.

    response.writeHead()总是在之前设定response.write().

    另请参阅我们已将响应类型设置为"text/html"


    http://nodejs.org/api/http.html#http_class_http_serverresponse

    2023-02-06 14:36 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有