Node.js HTTP Server对象及GET、POST请求

简介:

上一博客学习了请求与响应,2次读2次写,但有一个问题就是客户端写入的时候怎么知道请求到达。所以HTTP Server对象出现了。它提供了实现HTTP服务器的基本框架。它可以监听端口的底层套接字和接收请求,然后发送响应给客户端连接的处理程序。

它提供了一下几个事件:

request:当服务器收到客户端请求时触发。例如:function callback(request,response){}.

connection:当一个新的TCP流建立时触发。例如:function callback (socket)

close:服务器关闭时触发,回调不接收参数。

checkContinue:当收到包括期待的100-continue标头的请求时触发。即使不处理此事件,默认的事件处理程序也响应。例如:function callback(request,response){}

connect:接收到HTTP CONNECT请求时发出。callback接收request、response、head。例如:function callback(request,response,head)

upgrade:当客户端请求HTTP升级时发出。function callback (request,response,head)

clientError:当客户端连接套接字发出一个错误时发出。function callback(error,socket){}

要启动HTTP服务器,首先使用createServer([requestListener])方法创建对象然后通过listen(port,[hostname],[backlog],[callback]).

port:端口

hostname:主机名

backlog(积压):指定被允许进行排队的最大待处理连接数。默认511.

callback(回调):指定该服务器已经开始在指定的端口监听时,要执行的回调处理程序。

对于文件系统的连接可以用下面的两种方法:

listen(path,[callback]):文件路径

listen(handle,[callback]):接收一个已经打开的文件描述符句柄。

如果要停止监听可以使用close([callback])方法。

上面了解了下HTTP Server对象,下面用GET、POST实验一下。

GET:


var http = require('http');
var messages = [
  'Hello World',
  'From a basic Node.js server',
  'Take Luck'];
http.createServer(function (req, res) {
  res.setHeader("Content-Type", "text/html");
  res.writeHead(200);
  res.write('<html><head><title>Simple HTTP Server</title></head>');
  res.write('<body>');
  for (var idx in  messages){
    res.write('\n<h1>' + messages[idx] + '</h1>');
  }
  res.end('\n</body></html>');
}).listen(8080);

var options = {
    hostname: 'localhost',
    port: '8080',
  };
function handleResponse(response) {
  var serverData = '';
  response.on('data', function (chunk) {
    serverData += chunk;
  });
  response.on('end', function () {
    console.log("Response Status:", response.statusCode);
    console.log("Response Headers:", response.headers);
    console.log(serverData);
  });
}
http.request(options, function(response){
  handleResponse(response);
}).end();

Response Status: 200
Response Headers: { 'content-type': 'text/html',
  date: 'Mon, 28 Mar 2016 12:51:06 GMT',
  connection: 'close',
  'transfer-encoding': 'chunked' }
<html><head><title>Simple HTTP Server</title></head><body>
<h1>Hello World</h1>
<h1>From a basic Node.js server</h1>
<h1>Take Luck</h1>
</body></html>

POST:


var http = require('http');
http.createServer(function (req, res) {
  var jsonData = "";
  req.on('data', function (chunk) {
    jsonData += chunk;
  });
  req.on('end', function () {
    var reqObj = JSON.parse(jsonData);
    var resObj = {
      message: "Hello " + reqObj.name,
      question: "Are you a good " + reqObj.occupation + "?"
    };
    res.writeHead(200);
    res.end(JSON.stringify(resObj));
  });
}).listen(8088);


var http = require('http');
var options = {
  host: '127.0.0.1',
  path: '/',
  port: '8088',
  method: 'POST'
};
function readJSONResponse(response) {
  var responseData = '';
  response.on('data', function (chunk) {
    responseData += chunk;
  });

  response.on('end', function () {
    var dataObj = JSON.parse(responseData);
    console.log("Raw Response: " +responseData);
    console.log("Message: " + dataObj.message);
    console.log("Question: " + dataObj.question);
  });
}
var req = http.request(options, readJSONResponse);
req.write('{"name":"Bilbo", "occupation":"Burglar"}');
req.end();


Raw Response: {"message":"Hello Bilbo","question":"Are you a good Burglar?"}
Message: Hello Bilbo
Question: Are you a good Burglar?

第一次使用的时候用的端口号是8080,然后就报下面的错误.换一下端口号就OK了。


events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::8080
    at Object.exports._errnoException (util.js:870:11)
    at exports._exceptionWithHostPort (util.js:893:20)
    at Server._listen2 (net.js:1236:14)
    at listen (net.js:1272:10)
    at Server.listen (net.js:1368:5)
    at Object.<anonymous> (c:\Users\Administrator\Desktop\nodejs-mongodb-angularjs-web-development-master\ch07\http_server_post.js:16:4)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)

 以上基本把HTTP这块基本学了一下,对于HTTPS的话可以用HTTPS的客户端和服务端,和HTTP的差别不大,就是多了几个选项.

对于更底层的socket、tcp、udp这些就先跳过,这些做web可能也不会用到,大致学一遍之后再回过头来复习学习一下。


相关文章
|
17天前
|
JavaScript 前端开发 网络协议
前端JS发起的请求能暂停吗?
在讨论前端JS发起的请求是否能暂停时,需要明确两个概念:什么状态可以被认为是“暂停”?以及什么是JS发起的请求?
76 1
前端JS发起的请求能暂停吗?
|
6天前
|
网络协议 PHP
Swoole 源码分析之 Http Server 模块
想要了解到 `Http Server` 的全貌,其实只要把那张整体的实现图看懂就足以了。但是,如果想要有足够的深度,那么就还需要深入 `Swoole` 的源代码中,就着源码自行分析一遍。同时,也希望这一次的分析,能够给大家带来对 `Swoole` 更多的一些了解。并不要求要深刻的掌握,因为,很多的事情都不可能一蹴而就。从自己的实力出发,勿忘初心。
15 0
Swoole 源码分析之 Http Server 模块
|
17天前
|
JavaScript
Node.js GET/POST请求
Node.js GET/POST请求
11 1
|
20天前
|
小程序
Failed to load local image resource Xx the server responded with a status of of 500 (HTTP/1.1 500)
Failed to load local image resource Xx the server responded with a status of of 500 (HTTP/1.1 500)
|
24天前
|
缓存 安全 JavaScript
全面比较HTTP GET与POST方法
全面比较HTTP GET与POST方法
33 7
|
24天前
|
JSON 安全 Java
JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求
JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求
23 0
|
2月前
|
缓存 前端开发 JavaScript
React和Next.js开发常见的HTTP请求方法
React和Next.js开发常见的HTTP请求方法
27 0
|
Web App开发 存储 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
      前段时间公司hadoop集群宕机,发现是namenode磁盘满了, 清理出部分空间后,重启集群时,重启失败。 又发现集群Secondary namenode 服务也恰恰坏掉,导致所有的操作log持续写入edits.new 文件,等集群宕机的时候文件大小已经达到了丧心病狂的70G+..重启集群报错 加载edits文件失败。
871 0
|
Web App开发 前端开发
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
异步通信 对于BS(Browser-Server 浏览器)架构,很多情景下server的处理时间较长。 如果浏览器发送请求后,保持跟server的连接,等待server响应,那么一方面会对用户的体验有负面影响; 另一方面,很有可能会由于超时,提示用户服务请求失败。
744 0
|
Web App开发 前端开发 关系型数据库
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html><head><meta http-equiv="Cont
fuser可用于查询文件、目录、socket端口和文件系统的使用进程 1.查询文件和目录使用者 fuser最基本的用法是查询某个文件或目录被哪个进程使用: # fuser -v .
863 0