【问题标题】:Basic web server issuw with Node JsNode Js 的基本 Web 服务器问题
【发布时间】:2013-02-16 15:29:54
【问题描述】:

我是节点 js 的新手。我正在关注链接。但这总是执行response.writeHead(404); 所以我无法查看 index.html http://thecodinghumanist.com/blog/archives/2011/5/6/serving-static-files-from-node-js

这是我的网络服务器节点 js 代码。

var http = require('http');
var path = require('path');
var fs = require('fs');

http.createServer(function (request, response) {

    console.log('request starting...');

    var filePath = "."+request.url;
    if (filePath == './')
        filePath =  '/index.html';
    else
        console.log(request.url);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    fs.exists( filePath, function (exists) {
        console.log(filePath);
        if (exists) {

            fs.readFile(filePath, function (error, content) {
                if (error) {
                    console.log(error);
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': 'text/html' });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

}).listen(8125);

我的问题。

  1. 这没有显示 index.html。
  2. 如何根据不同的请求发送响应或 html 文件? 例如:http://localhost:8125 -> index.html http://localhost:8125/firstpage.html -> firstpage.html
  3. 我们是否需要将 html 文件放在包含 server.js(Web 服务器)的同一目录中?

我也在 cloud9 ide 中尝试过。

我在 SO 中发现了类似的问题。但我没有明确的想法如何解决它。 Node.js - Socket.io client file not being served by basic node web server 提前致谢。

【问题讨论】:

    标签: windows node.js


    【解决方案1】:

    1- 是的,没错。我可以重现错误。我对教程不熟悉,但显然filePath = '/index.html'; 应该是filePath = './index.html';

    否则服务器正在寻找“/index.html”,即文件系统根目录中名为“index.html”的文件,而不是当前目录。也许它在 Windows 操作系统上工作,但在 *nix 上这将不起作用。我你加了.,index.html就送达了。

    2- 为此,您需要导入“url”node.js 模块,然后您可以使用一种便捷的方式来解析 URL:http://nodejs.org/api/http.html#http_request_url 基本上,在fs.exist ... 行之前,您可以添加以下内容:

    var requestedfile = urlparser.parse(request.url).pathname;
    console.log("requested URL path name : " + requestedfile);

    然后您将能够处理不同的请求。

    3- 是的,你可以。请记住,当添加一个点“。”在问题 1 的“index.html”之前,您提供了 index.html 的相对路径(相对于 server.js 在文件系统上的位置)。因此,您可以通过这种方式指定任何其他相对路径。

    如果您将页面存储在当前文件夹之外的另一个目录中(例如 /var/www/mysite),您仍然可以通过将包含此绝对路径的字符串变量与请求路径名连接起来来提供这些页面。 例如(虽然经过测试)

    var pagestorage = "/var/www/mysite/";
    (...)
    var pathname = urlparser.parse(request.url).pathname;
    var requestfile = pagestorage + pathname;
    

    这是更新文件的完整示例:

     var http = require('http');
    var path = require('path');
    var fs = require('fs');
    var urlparser = require('url');
    
    http.createServer(function (request, response) {
    
        console.log('request starting...');
    
        var filePath = "."+request.url;
        if (filePath == './')
            filePath =  './index.html';
        else
            console.log(request.url);
        var extname = path.extname(filePath);
        var contentType = 'text/html';
        switch (extname) {
            case '.js':
                contentType = 'text/javascript';
                break;
            case '.css':
                contentType = 'text/css';
                break;
        }
    
        // documentation at : http://nodejs.org/api/http.html#http_request_url
        var requestedfile = urlparser.parse(request.url).pathname;
        console.log("requested URL path name : " + requestedfile);
    
        fs.exists( filePath, function (exists) {
            console.log("looking up : " + filePath);
            if (exists) {
    
                fs.readFile(filePath, function (error, content) {
                    if (error) {
                        console.log("error" + error);
                        response.writeHead(500);
                        response.end();
                    }
                    else {
                        response.writeHead(200, { 'Content-Type': 'text/html' });
                        response.end(content, 'utf-8');
                    }
                });
            }
            else {
                response.writeHead(404);
                response.end();
            }
        });
    
    }).listen(8125);
    

    HTH

    【讨论】:

      猜你喜欢
      • 2015-08-17
      • 2016-09-14
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-08-27
      • 2015-12-31
      • 2018-01-10
      相关资源
      最近更新 更多