首页 > Web开发 > 详细

在node.js中建立你的第一个HTTp服务器

时间:2017-03-23 14:06:18      阅读:191      评论:0      收藏:0      [点我收藏+]

这一章节我们将从初学者的角度介绍如何建立一个简单的node.js HTTP 服务器

 

创建myFirstHTTPServer.js

//Lets require/import the HTTP module
var http = require(‘http‘);

//Lets define a port we want to listen to
const PORT=8080; 

//We need a function which handles requests and send response
function handleRequest(request, response){
    response.end(‘It Works!! Path Hit: ‘ + request.url);
}

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

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

使用node 运行文件

> node myFirstHTTPServer.js

#output
Server listening on: http://localhost:8080

上述已经在浏览器上打开了 http://localhost:8080   

  

分析:

//Lets require/import the HTTP module
var http = require(‘http‘);

node.js有用于穿件http/https 的 核心模块,因此我们只需引入http模块就可创建一个HTTP 服务器

//We need a function which handles requests and send response
function handleRequest(request, response){
    response.end(It Works!! Path Hit:  + request.url);
}

我们需要一个用来处理所有请求和响应的函数

上述代码是你服务器项目的入口点(即 你可以根据你的业务逻辑来响应请求)

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

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

上述,创建了一个吸金的HTTP服务器对象,并要求其监听一个端口

createServer方法用来创建一个新的服务器实例并且使用监听函数作为参数

然后,我们即可调用监听在服务器上的函数来启动服务器

 

 

上述是基本的HTTP服务器运行

现在我们添加一些实际需求

 

对于不同的URL路径,你的服务器应该有不同的响应

这意味着我们需要一个dispatcher

dispatcher是一种路由(router),在针对不同的指定URL路径时,你可用其来调用你想调用的请求处理函数代码。

第一:安装dispatcher 模块

有很多不同的模块,针对演示例子,我们安装了基本的模块

> npm install httpdispatcher

注意:nmp是一个包管理器,其提供了针对js和nodeJs的核心开源模块。我们使用 ‘npm install ’命令就可安装所有所需的模块

下面,使用dispatcher模块

var dispatcher = require(‘httpdispatcher‘);

接着,让dispatcher在监听函数中运行

//Lets use our dispatcher
function handleRequest(request, response){
    try {
        //log the request on console
        console.log(request.url);
        //Disptach
        dispatcher.dispatch(request, response);
    } catch(err) {
        console.log(err);
    }
}

让我们定义一些路由

路由定义了当浏览器请求一个特地的URL时,服务器应该做什么

//For all your static (js/css/images/etc.) set the directory name (relative path).
dispatcher.setStatic(resources);

//A sample GET request    
dispatcher.onGet("/page1", function(req, res) {
    res.writeHead(200, {Content-Type: text/plain});
    res.end(Page One);
});    

//A sample POST request
dispatcher.onPost("/post1", function(req, res) {
    res.writeHead(200, {Content-Type: text/plain});
    res.end(Got Post Data);
});

现在让我们尝试不同的地址:

  • GET /page1 => ‘Page One‘
  • POST /page2 => ‘Page Two‘
  • GET /page3 => 404
  • GET /resources/images-that-exists.png => Image resource
  • GET /resources/images-that-does-not-exists.png => 404

 你可通过在浏览器地址栏输入URL来进行一个get请求。针对Post请求,你可使用Postman工具

 

ok!你现在已经可以建立一个简单的HTTP服务器并且使之运行了!

上述我们创建了一个基本的HTTP服务器,其创建是通过使用 http模块和 一个简单的dispatcher模块 来实现的, displatcher是用来分配(dispatch)http请求到合适的路由上。

 

 

  

在node.js中建立你的第一个HTTp服务器

原文:http://www.cnblogs.com/RachelChen/p/6604369.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!