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

标签 javascript html node.js

我正在使用 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 或任何东西。

最佳答案

我,

在您的 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

关于javascript - Node.js 服务器 "404 not found"消息到 404.html 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20933510/

相关文章:

javascript - Angular UI-router 设置网站入口点。重定向到主页 URL

javascript - 如何使div可以点击?

html - 在android中使用html5在webview中播放mp4视频

node.js - 没有嵌套 node_modules 的 NPM 安装包

c# - 如何解析 Json.NET 多态对象?

javascript - AJAX - 如何从输入文件中获取数据以附加表单数据?

node.js - 找不到 Protractor 结果文件夹 'protractor-html-screenshot-reporter'

node.js - 在 serverless.yml 中创建两个 dynamoDB 表

javascript - 对 StackExchange API 的 HTTP GET 请求不会在 AngularJS 应用程序中返回

javascript - 复制和粘贴时不允许在文本框中使用小数和文本值