这一章节我们将从初学者的角度介绍如何建立一个简单的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(, {'Content-Type': 'text/plain'});
res.end('Page One');
}); //A sample POST request
dispatcher.onPost("/post1", function(req, res) {
res.writeHead(, {'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服务器的更多相关文章

  1. node.js中通过dgram数据报模块创建UDP服务器和客户端

    node.js中 dgram 模块提供了udp数据包的socket实现,可以方便的创建udp服务器和客户端. 一.创建UDP服务器和客户端 服务端: const dgram = require('dg ...

  2. node.js中使用http-proxy-middleware请求转发给其它服务器

    var express = require('express');var proxy = require('http-proxy-middleware'); var app = express(); ...

  3. node.js中使用http模块创建服务器和客户端

    node.js中的 http 模块提供了创建服务器和客户端的方法,http 全称是超文本传输协议,基于 tcp 之上,属于应用层协议. 一.创建http服务器 const http = require ...

  4. Node.js中的Session,不要觉得简单哦。

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,博客地址为http://www.cnblogs.com/jasonnode/ .学习网站上有对应 ...

  5. node.js中process进程的概念和child_process子进程模块的使用

    进程,你可以把它理解成一个正在运行的程序.node.js中每个应用程序都是进程类的实例对象. node.js中有一个 process 全局对象,通过它我们可以获取,运行该程序的用户,环境变量等信息. ...

  6. node.js中net网络模块TCP服务端与客户端的使用

    node.js中net模块为我们提供了TCP服务器和客户端通信的各种接口. 一.创建服务器并监听端口 const net = require('net'); //创建一个tcp服务 //参数一表示创建 ...

  7. node.js中net模块创建服务器和客户端(TCP)

    node.js中net模块创建服务器和客户端 1.node.js中net模块创建服务器(net.createServer) // 将net模块 引入进来 var net = require(" ...

  8. node.js中http通讯模块

    创建一个服务器 首先建立一个js文件,命名为app.js写入内容: const http=require('http'); http.createServer((request,response)=& ...

  9. node.js中的路由(url)初步

    1.建立n4_root.js var http = require('http'); var url = require('url'); //这是node.js中自带的var router = req ...

随机推荐

  1. Hibernate4.3.6 Final+Spring3.0.5配置出错提示及解决方法

    1. Caused by: org.hibernate.cache.NoCacheRegionFactoryAvailableException: Second-level cache is used ...

  2. Hessian原理与程序设计

     Hessian是比較经常使用的binary-rpc.性能较高,适合互联网应用.主要使用在普通的webservice 方法调用.交互数据较小的场景中.hessian的数据交互基于http协议,通常he ...

  3. 获取服务器classes根路径

    /** * 获取web应用路径 * @Description : 方法描述 * @Method_Name : getRootPath * @return * @return : String * @C ...

  4. 使用struts2完成ckeditor和图片上传

    代码地址如下:http://www.demodashi.com/demo/12427.html 使用struts2完成ckeditor和ckeditor图片上传 ckeditor版本ckeditor_ ...

  5. Centos7 安装 Maven 3.5.*

    下载 Apache Maven 访问 Maven官方网站,打开后找到下载链接,如下: 解压 tar zxvf apache-maven-3.5.3-bin.tar.gz 添加环境变量 打开 /etc/ ...

  6. H5和CSS3新增内容总结

    CSS3选择器有哪些?答:属性选择器.伪类选择器.伪元素选择器.CSS3新特性有哪些?答:1.颜色:新增RGBA,HSLA模式 文字阴影(text-shadow.) 边框: 圆角(border-rad ...

  7. [转]Linux shell中的那些小把戏

    我日常使用Linux shell(Bash),但是我经常忘记一些有用的命令或者shell技巧.是的,我能记住一些命令,但是肯定不会只在特定的任务上使用一次,所以我就开始在我的Dropbox账号里用文本 ...

  8. Scrapy安装向导

    原文地址 https://doc.scrapy.org/en/latest/intro/install.html 安装Scrapy Scrapy运行在python2.7和python3.3或以上版本( ...

  9. ReactiveCocoa入门教程——第一部分【转载】

    作为一个iOS开发者,你写的每一行代码几乎都是在响应某个事件,例如按钮的点击,收到网络消息,属性的变化(通过KVO)或者用户位置的变化(通过CoreLocation).但是这些事件都用不同的方式来处理 ...

  10. linux SPI驱动——gpio模拟spi驱动(三)

    一:首先在我的平台注册platform_device,保证能让spi-gpio.c能执行到probe函数. 1: struct spi_gpio_platform_data { 2: unsigned ...