回顾
- 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();
}
});
});