您的位置:首页 > 理论基础 > 计算机网络

04全栈工程师--2016-08-09

2016-08-09 23:15 309 查看

回顾

HTTP协议

Request对象

Reponse对象

Nodejs创建服务器模块

Nodejs创建一个静态资源服务器

http模块 const http = require(‘http’);

url模块 const url = require(‘url’);

fs模块 const fs = require(‘fs’);

创建一个服务器

var port = 8000;
var ip = '127.0.0.1';
var http = require('http);

var server = http.createServer(function(request,reponse){

reponse.writeHead(200,{'Content-Type':'text/plain'});
reponse.write('hellow Nodejs');
reponse.end();

}).listen(port,ip);


实现路由,获取URL

var url = require('url');
var pathname = url.parse(request.url).pathname;

var server = http.createServer(function(request,reponse){

var pathname = url.parse(request.url).pathname;
reponse.write(pathname);
reponse.end();

});


读取静态文件

var fs = require('fs');
var path = require('path');
var sever = http.createServer(function(request,reponse){
var pathname = url.parse(request.url)pathname;
var realPath = 'assets' + pathname;

path.exists(realPath,function(exists){
if(!esists){
reponse.write(404,{'Content-Type':'texty/plain'});
reponse.write('This request url' + pathname + 'not exists in server');
reponse.end();
}else{

fs.readFile(realPath, "binary", function(err, file) {
if (err) {
response.writeHead(500, {‘Content-Type‘: ‘text/plain‘});
response.end(err);

} else {
response.writeHead(200, {‘Content-Type‘: ‘text/html‘});
response.write(file, "binary");
response.end();
}
});
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息