在node.js中建立你的第一个HTTp服务器
这一章节我们将从初学者的角度介绍如何建立一个简单的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服务器的更多相关文章
- node.js中通过dgram数据报模块创建UDP服务器和客户端
node.js中 dgram 模块提供了udp数据包的socket实现,可以方便的创建udp服务器和客户端. 一.创建UDP服务器和客户端 服务端: const dgram = require('dg ...
- node.js中使用http-proxy-middleware请求转发给其它服务器
var express = require('express');var proxy = require('http-proxy-middleware'); var app = express(); ...
- node.js中使用http模块创建服务器和客户端
node.js中的 http 模块提供了创建服务器和客户端的方法,http 全称是超文本传输协议,基于 tcp 之上,属于应用层协议. 一.创建http服务器 const http = require ...
- Node.js中的Session,不要觉得简单哦。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,博客地址为http://www.cnblogs.com/jasonnode/ .学习网站上有对应 ...
- node.js中process进程的概念和child_process子进程模块的使用
进程,你可以把它理解成一个正在运行的程序.node.js中每个应用程序都是进程类的实例对象. node.js中有一个 process 全局对象,通过它我们可以获取,运行该程序的用户,环境变量等信息. ...
- node.js中net网络模块TCP服务端与客户端的使用
node.js中net模块为我们提供了TCP服务器和客户端通信的各种接口. 一.创建服务器并监听端口 const net = require('net'); //创建一个tcp服务 //参数一表示创建 ...
- node.js中net模块创建服务器和客户端(TCP)
node.js中net模块创建服务器和客户端 1.node.js中net模块创建服务器(net.createServer) // 将net模块 引入进来 var net = require(" ...
- node.js中http通讯模块
创建一个服务器 首先建立一个js文件,命名为app.js写入内容: const http=require('http'); http.createServer((request,response)=& ...
- node.js中的路由(url)初步
1.建立n4_root.js var http = require('http'); var url = require('url'); //这是node.js中自带的var router = req ...
随机推荐
- vue 监听 watch 使用
1.api https://cn.vuejs.org/v2/api/#watch 有2个配置: (1)深度 watcher deep: true(2)该回调将会在侦听开始之后被立即调用 immedia ...
- 在非主线程中更新UI
在非主线程中调用了showMessage方法,结果报错:Can't create handler inside thread that has not called Looper.prepare() ...
- apache common包 CollectionUtils 使用 详解
集合判断: 例1: 判断集合是否为空: CollectionUtils.isEmpty(null): true CollectionUtils.isEmpty(new ArrayList()): t ...
- Android TelephonyManager类的使用
TelephonyManager类主要提供了一系列获取手机与通讯相关的状态和信息的get方法,包含手机用户的信息.手机SIM的状态.电信网络的状态等. TelephonyManager类的对象的获取: ...
- hashmap和ConcurrentHashMap
hashmap市基于table和单向链表 table中存放hash值,table中存放着单向链表,查询时先计算对象hash值,找到table中对应值,然后查询链表. ConcurrentHashMap ...
- OS开发之旅之App的生命周期【转载】
原文链接 http://www.360doc.com/content/15/0918/14/27799428_499912639.shtml 在iOS App中,入口函数并不在根目录下,而是在“Sup ...
- Win7获取管理权限修改Host文件以其他权限问题
——win7管理员权限修改Host文件——百度经验 win7管理员权限获取办法: win7管理员权限 获取办法——经验——百度 win7最高权限获取: win7最高权限 获取——百度经验
- java8笔记: sorted()之正序倒序
java8笔记: sorted()之正序倒序 这篇文章将会讲解Java 8 Stream sorted()示例 下面代码以自然序排序一个list List<Person> listTem ...
- PowerBuilder -- 日期控件
MonthCalendar
- 【BZOJ】1003 Cards
[解析]Burnside引理+背包dp+乘法逆元 [Analysis] 这道题卡了好久,就是没想懂置换跟着色是不一样的. 依据burnside引理.在一个置换群作用下不等价类的个数为每一个置换作用下不 ...