这一章节我们将从初学者的角度介绍如何建立一个简单的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. jmeter之怎样减负-实现稳定超高并发測试(性能调优)

    新浪围脖>@o蜗牛快跑o    在測试过程中,刚開始学习的人(也包含早期的我),使用工具不当,加入众多监控组件,很想看到实时报告.跑不了一会,jmeter就卡死甚至oom.仅仅得重新启动.之前的 ...

  2. struts2获取ServletContext对象

      CreateTime--2017年9月7日09:24:40 Author:Marydon struts2获取ServletContext对象 需要导入: import javax.servlet. ...

  3. Java 调用OPENOFFIC 转换文档类型

    public static void office2PDF(String sourceFile, String destFile) { try { File inputFile = new File( ...

  4. wpf SplitButton

     SplitButton该控件除了本身Button 的功能外,还具有下拉菜单的功能,能够在按键右側加入下拉菜单控件: <SplitButton Content="..." ...

  5. 敏捷DoD完毕定义的多种形态

    作者:张克强    作者微博:张克强-敏捷307 关于Definition of Done 完毕的定义 在以往的说法中,常见用 退出标准 , 完毕条件.成功标准,等等 在敏捷软件开发中,存在多级的不同 ...

  6. Ajax请求的跨域(CORS)问题

    用浏览器,通过XHR(XMLHttpRequest)请求向另外一个域名请求数据时.会碰到跨域(CORS)问题. CORS:Cross-Origin Resource Sharing 什么是跨域? 简单 ...

  7. jdbc 链接池的优化

    package cn.itcast.jdbc.datasourse; import java.sql.Connection;import java.sql.DriverManager;import j ...

  8. Java异常 - Exception总结

    这篇blog总结的比较详细了. 如下图所示,在Java中所有异常的基类均为Throwable类.有两个子类,分别为Exception和Error.其中Error主要由JVM处理,比如OutOfMemo ...

  9. easyUI中 datagrid 格式化日期

    $('#List').datagrid({ url: '@Url.Action("GetList")', width:SetGridWidthSub(10), methord: ' ...

  10. python 基础 3.1 打开文件 a a+ r+ w+ 详解

      一.python 访问文件   1.在python中要访问文件,首先要打开文件,也就是open ---open   r:  只读   w:  只写 ,文件已存在则清空,不存在则创建   a:追加 ...