javascript Node.js 服务器“404 未找到”消息到 404.html 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20933510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:39:10  来源:igfitidea点击:

Node.js server "404 not found" message to 404.html page

javascripthtmlnode.js

提问by Rob Sedgwick

Im working with node.js and I would like to know how to display a 404.html instead of a "404 Not Found" message.

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

This is my server.js:

这是我的 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");

as you can see its just a static file server and I'm not using express.js or anything.

正如你所看到的,它只是一个静态文件服务器,我没有使用 express.js 或任何东西。

回答by Rob Sedgwick

H i ,

你好 ,

within your 404 case

在您的 404 案例中

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

You can change to

您可以更改为

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

'HTMLDATA'being either a string of HTML or a reference to a file you have gathered.

'HTMLDATA'要么是一个 HTML 字符串,要么是对您收集的文件的引用。

response.writeHead()is always set before the response.write().

response.writeHead()始终设置在response.write().

Also see we have set the response type to 'text/html'

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



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

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

回答by StarsSky

response.writeHead(404, {
  'Location': 'your/404/path.html'
  //add other headers here...
});
response.end();

or with a single line

或单行

response.redirect('your/404/path.html');

回答by Ilan Frumer

Just load 404.html using fs.readFile and serve it with response.write

只需使用 fs.readFile 加载 404.html 并使用 response.write 提供它

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) {
  fs.readFile('404.html', "binary", function(err, file) {
    if(err) {
       response.writeHead(404, {"Content-Type": "text/html"});
       response.write("404 Not Found\n");
    } else {
       response.writeHead(404);
       response.write(file, "binary");            
    }
    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");`enter code here`

回答by farvilain

Do just for the 200... Read a file 404.html and write it to the response, just set the code 404 in writeHead.

只为 200 做...读取文件 404.html 并将其写入响应,只需在 writeHead 中设置代码 404。

回答by Fizer Khan

This might be more of what you're looking for.

这可能是您正在寻找的更多内容。

    fs.readFile('404.html', function(error, data) {
        res.writeHead(404, {'content-type': 'text/html'});
        res.end(data);
    });