zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JSserverNode对象HTTP 请求 get post
2023-09-14 08:57:59 时间

上一博客学习了请求与响应,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);


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可能也不会用到,大致学一遍之后再回过头来复习学习一下。



开心档-Node.js GET/POST请求 在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交。 表单提交到服务器一般都使用 GET/POST 请求。 本章节我们将为大家介绍 Node.js GET/POST请求。
开心档-软件开发入门之Node.js GET/POST请求 在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如表单提交。 表单提交到服务器一般都使用 GET/POST 请求。 本章节我们将为大家介绍 Node.js GET/POST请求。
社会主义 从.Net到iOS,在撸的道路上越走越远,工作之余经营着博客园http://www.cnblogs.com/5ishare,欢迎小伙伴(妹子更好)一起交流,谈谈人生理想。作为经常从网上索取免费资料的一员,要有回报回报的思想,也让更多的人少走弯路.