Node-Web模块
生活随笔
收集整理的这篇文章主要介绍了
Node-Web模块
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
创建服务端------------------------------------------------------var http = require('http');
var fs = require('fs');
var url = require('url');// 创建服务器
http.createServer( function (request, response) { // 解析请求,包括文件名var pathname = url.parse(request.url).pathname;// 输出请求的文件名console.log("Request for " + pathname + " received.");// 从文件系统中读取请求的文件内容fs.readFile(pathname.substr(1), function (err, data) {if (err) {console.log(err);// HTTP 状态码: 404 : NOT FOUND// Content Type: text/htmlresponse.writeHead(404, {'Content-Type': 'text/html'});}else{ // HTTP 状态码: 200 : OK// Content Type: text/htmlresponse.writeHead(200, {'Content-Type': 'text/html'}); // 响应文件内容response.write(data.toString()); }// 发送响应数据response.end();});
}).listen(8080);// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:8080/');创建客户端------------------------------------------------------
var http = require('http');// 用于请求的选项
var options = {host: 'localhost',port: '8080',path: '/index.html'
};// 处理响应的回调函数
var callback = function(response){// 不断更新数据var body = '';response.on('data', function(data) {body += data;});response.on('end', function() {// 数据接收完成console.log(body);});
}
// 向服务端发送请求
var req = http.request(options, callback);
req.end();
总结
以上是生活随笔为你收集整理的Node-Web模块的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: node-OSDomainNetPath
- 下一篇: Node-Web应用框架Express