个性化阅读
专注于IT技术分析

在Node.js中创建第一个自我实现的基本HTTP服务器(带有路由)

点击下载

Web服务器是通过HTTP处理请求的系统, HTTP是用于在Web上或本地分发信息的基本网络协议。你可以使用Node.js的http模块从网络请求内容, 甚至创建自己的http服务器来回答其响应, 提供文件等。

在本文中, 你将学习如何使用http模块和httpdispatcher模块来实现自写的http服务器, 以添加路由功能。

实现

首先, 创建一个名为server.js的JS文件, 它将包含以下代码来创建和处理基本的http服务器:

注意:http模块已经内置在node.js中, 因此你无需下载任何模块。除非还没有。

// require the http module of node.js
var http = require('http');

// define the port of access for your server
const PORT = 8080;

// We need a function which handles requests and send response
function handleRequest(request, response){
    response.end('Server working properly. Requested URL : ' + request.url);
}

// Create a server
var myFirstServer = http.createServer(handleRequest);

// Start the server !
myFirstServer.listen(PORT, function(){
    // Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});

createServer方法返回http.Server的新实例。要创建我们的服务器, 你需要指定一个端口并使用listen方法, 这将导致服务器接受指定句柄上的连接。

要启动服务器, 请在Node.js命令提示符中使用以下命令:

node server.js

现在, 打开你喜欢的浏览器并导航到http:// localhost:8080, 你将收到以下响应(并且应根据给定的URL进行更改):

HTTP服务器Node.js

如你所见, 服务器将回答所有URL地址。

请注意, http模块非常简单, 使用上一示例创建复杂的Web应用程序将花费大量时间来正确实施, 因此你应将上一示例用于服务文件或学习目的的简单事物。如果你正在处理复杂的项目, 则应为其使用框架, 例如Express, hapi, koa或restify。在本文中, 你将学习如何使用httpdispatcher模块创建基本的路由系统。

添加路由功能

如前所述, 你的服务器现在返回任何URL的响应, 因此, 要添加一些”现实生活”功能, 你的服务器需要响应特定的URL地址。

为了在这个基本示例中处理此问题, 我们需要使用一个调度程序, 它将作为一种路由器, 使你可以对特定的URL做出不同的响应。 httpdispatcher是一个简单的类, 允许开发人员为动态页面和静态资源提供清晰的分派器。

要将http调度程序添加到你的项目中, 请在Node.js命令提示符下添加执行以下命令的模块:

npm install httpdispatcher

现在, 让我们在示例中使用分派器添加一些路由:

// require the http module of node.js
var http = require('http');
// require the dispatcher module
var dispatcher = require('httpdispatcher');

// define the port of access for your server
const PORT = 8080;

// We need a function which handles requests and send response
function handleRequest(request, response){
    try {
        // log the request on console
        console.log(request.url);
        // Dispatch
        dispatcher.dispatch(request, response);
    } catch(err) {
        console.log(err);
    }
}

// Create a server
var myFirstServer = http.createServer(handleRequest);

// add some routes

//A sample GET request
dispatcher.onGet("/", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h1>Hey, this is the homepage of your server</h1>');
});

dispatcher.onGet("/welcome", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Welcome homepage');
});

dispatcher.onError(function(req, res) {
    res.writeHead(404);
    res.end("Error, the URL doesn't exist");
});

// Start the server !
myFirstServer.listen(PORT, function(){
    // Callback triggered when server is successfully listening. Hurray!
    console.log("Server listening on: http://localhost:%s", PORT);
});

httpdispatcher模块使你可以轻松地为不同的请求格式(POST, GET)创建路由和响应, 并且如所承诺的那样, 你现在已经拥有一个由Node.js构成的功能性http服务器, 以启动它执行:

node server.js

如果导航到http:// localhost:8080和http:// localhost:8080 / welcome, 你将分别看到示例中给出的响应。如果你尝试访问一个不存在的URL(即http:// localhost:8080 / this-doesnt-exists), 则会收到404响应, 提示”错误, URL不存在”。

如果你需要更强大的功能, 可以阅读我们的教程”如何使用Express创建HTTP服务器以实现高可伸缩性项目”。

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 在Node.js中创建第一个自我实现的基本HTTP服务器(带有路由)

评论 抢沙发

评论前必须登录!