codecamp

Node.js HTTP

以下是在Node.js中创建Web应用程序的主要核心网络模块:

net / require("net")            the foundation for creating TCP server and clients 
dgram / require("dgram")        functionality for creating UDP / Datagram sockets 
http / require("http")          a high-performing foundation for an HTTP stack 
https / require("https")        an API for creating TLS / SSL clients and servers 

http模块有一个函数createServer,它接受一个回调并返回一个HTTP服务器。

在每个客户端请求,回调传递两个参数 - 传入请求流和传出服务器响应流。

要启动返回的HTTP服务器,请调用其在端口号中传递的listen函数。

例子

下面的代码提供了一个简单的服务器,监听端口3000,并简单地返回“hello client!” 每个HTTP请求

var http = require("http"); 
//from www.w3cschool.cn
var server = http.createServer(function (request, response) { 
    console.log("request starting...");
     // respond 
    response.write("hello client!"); 
    response.end(); 
}); 
server.listen(3000); 
console.log("Server running at http://127.0.0.1:3000/"); 

要测试服务器,只需使用Node.js启动服务器。

$ node 1raw.js 
Server running at http://127.0.0.1:3000/ 

然后在新窗口中使用curl测试HTTP连接。

$ curl http://127.0.0.1:3000 
hello client! 

要退出服务器,只需在服务器启动的窗口中按Ctrl + C。

检查接头

curl发送的请求包含几个重要的HTTP标头。

为了看到这些,让我们修改服务器以记录在客户端请求中接收的头。

var http = require("http"); 
//www.w3cschool.cn
var server = http.createServer(function (req, res) { 
    console.log("request headers..."); 
    console.log(req.headers);
     // respond 
    res.write("hello client!"); 
    res.end(); 
}).listen(3000); 
console.log("server running on port 3000"); 

现在启动服务器。

我们将要求curl使用-i选项注销服务器响应头。

$ curl http://127.0.0.1:3000 -i 
HTTP/1.1 200 OK 
Date: Thu, 22 May 2014 11:57:28 GMT 
Connection: keep-alive 
Transfer-Encoding: chunked 

hello client! 

如你所见,req.headers是一个简单的JavaScript对象字面量。你可以使用req ['header-name']访问任何标头。

设置状态代码

默认情况下,状态代码为200 OK。

只要标头未发送,你就可以使用statusCode响应成员设置状态代码。

response.statusCode = 404; 
Node.js 自定义流
Node.js HTTP标头
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }