基本HTTP服务器w / Node JS

时间:2015-06-03 05:36:47

标签: node.js http server

我有点陷入困境。我是一般的编码新手,这是我本周为我的JavaScript课程指定的程序。我们应该创建一个Web服务器来提供文件系统中的文件,该文件系统也实现了Node模块。它必须能够读取HTML,css,gif和js资源。这些文件将放在与脚本相同的文件夹中,位于/ scripts和/ html目录下。这是我试图实现的逻辑,但是我的终端一直告诉我path.extname(resource)是一个未定义的函数。我知道,这很难看,但我仍然试图围绕这个概念。任何帮助都会很棒,我一直试图在过去的一天解决这个问题。

'use strict';

// Load the file system module
var fs = require('fs');

// load the http module
var http = require('http');

// load the url module
var url = require('url');

// load the path module
var pathModule = require('path');


// The following function will be called when the server
// is handling a request

function servePage(request, response) {
    // get path name and remove '/'
    var path = url.parse(request.url).pathname.substring(1);

    // if path is an empty string
    if (path === '') {
        path = './html/home.html';
    }

    // Read the file asynchronously; HTML
    fs.readFile(path, function (err, content) {

        var extension = path.extname(path);

        switch (extension){
            case '.hmtl':
                response.writeHead(200,
                {'Content-Type': 'image/gif'});
            response.write(content); // Send file contents as response body
            response.end();
            break;

            case '.gif':
                response.writeHead(200,
                {'Content-Type': 'text/html; charset = UTF-8'});
            response.write(content); // Send file contents as response body
            response.end();
            break;

            case '.css':
                response.writeHead(200,
                {'Content-Type': 'text/css; charset = UTF-8'});
            response.write(content); // Send file contents as response body
            response.end();
            break;

            case '.js':
                response.writeHead(200,
                {'Content-Type': 'application/javascript; charset = UTF-8'});
            response.write(content); // Send file contents as response body
            response.end();
            break;

            case 'err':
            response.writeHead(404, 
                {'Content-Type': 'text/plain; charset = UTF-8'});
            response.write(err.message + 
                ' - The page requested was not found.');
            response.end(); // Done
            break;
        }



        /* }
        if (err) { // If there is an error, set the status code
            response.writeHead(404, 
                {'Content-Type': 'text/plain; charset = UTF-8'});
            response.write(err.message + 
                ' - The page requested was not found.');
            response.end(); // Done
            // else if the content was succesfully read
        } else {
            response.writeHead(200,
                {'Content-Type': 'text/html; charset = UTF-8'});
            response.write(content); // Send file contents as response body
            response.end();
        } */
    });
}







// create a server object
var server = http.createServer(servePage);
server.listen(8080);

console.log('Server running at http://localhost:8080');

3 个答案:

答案 0 :(得分:2)

请使用快速框架,这将使您的工作轻松。

var express = require('express');
app.use("/",  express.static(__dirname + '/client/'));
app.listen(3000,function(){
console.log("App Started on PORT 3000");
});

这里你的客户端文件夹将包含所有文件,即gif,html等。

答案 1 :(得分:2)

以下是重构代码的方法。

'use strict';
var fs = require('fs');
var http = require('http');
var url = require('url');
var path = require('path');

function getContentType(ext) {
    switch (ext.toLowerCase()) {
        case '.html': return 'text/html; charset=UTF-8';
        case '.gif':  return 'image/gif';
        case '.css':  return 'text/css; charset=UTF-8';
        case '.js':   return 'application/javascript; charset=UTF-8';
        default:      return 'text/plain; charset=UTF-8';
    }
}

var server = http.createServer(function (request, response) {
    // This is dangerous.
    var filePath = url.parse(request.url).pathname.substring(1);
    if (filePath === '') {
        filePath = './html/home.html';
    }

    fs.readFile(filePath, function (err, content) {
        var statusCode = 200,
            headers = {
                'Content-Type': getContentType(path.extname(filePath))
            };

        if (err) {
            statusCode = 404;
            headers['Content-Type'] = getContentType('.txt');
            content = 'The page requested was not found.\n\n' + err.message;
        }

        response.writeHead(statusCode, headers);
        response.write(content);
        response.end();
        console.log('' + statusCode + ': ' + filePath);
    });
});

server.listen(8080);
console.log('Server running at http://localhost:8080');

注意这个

var filePath = url.parse(request.url).pathname.substring(1);

很危险。想想当有人要求/../../foo/bar时会发生什么。

答案 2 :(得分:1)

您的path变量已分配给字符串 而你的路径是'模块已分配给pathModule

因此没有函数可以调用path(因为它是一个字符串)

您应该将其更改为pathModule.extname();