http.createServer( function (request, response) {}).listen(8080);
createServer 方法 可以创建一个客户端和服务器端响应请求。
function 回调函数处理的就是 接收过程。
request 就是 所有请求信息
response 所有响应信息
listen 方法 监听端口
//index.html页面
<link rel="stylesheet" href="./static/1.css">
<body>
<img src="./static/2.jpg" alt="">
<h1>我是首页</h1>
<img src="/static/1.jpg" alt="">
<a href="./aboutus?id=10">关于我们</a><br>
<form action="/aboutus" method="POST">
<button type="submit">提交</button>
</form>
</body>
<script src="./static/1.js"></script>
//aboutus.html页面
<body>
<h1>关于我们<%=query%></h1>
<img src="/static/1.jpg" alt="">
</body>
纯地址页面,不传参数写法 request.url纯地址
var fs = require('fs');
var http = require('http');
var url = require('url');
var querystring = require('querystring');
http.createServer(function(request,response){
if(request.url == '/'){
response.write(fs.readFileSync('./index.html'));
response.end();
}else if(request.url == '/aboutus'){
response.write(fs.readFileSync('./aboutus.html'));
response.end();
}
}).listen(8080);
//传参写法
http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname; //请求地址pathname
var pathInfo = pathname.split('.');
if(pathInfo[pathInfo.length-1] == 'css'){ //处理css
response.writeHead(200,{'Content-Type':'text/css'});
var rs = fs.readFileSync('./'+pathname);
response.write(rs);
response.end();
}
if( pathInfo[pathInfo.length-1] == 'jpg' ||
pathInfo[pathInfo.length-1] == 'ico' ||
pathInfo[pathInfo.length-1] == 'png' ||
pathInfo[pathInfo.length-1] == 'gif'){
if(pathInfo[pathInfo.length-1] == 'jpg'){ //处理图片
response.writeHead(200,{'Content-Type':'image/jpeg'});
}else if(pathInfo[pathInfo.length-1] == 'ico'){
response.writeHead(200,{'Content-Type':'image/x-icon'});
}else{
response.writeHead(200,{'Content-Type':'image/'+pathInfo[pathInfo.length-1]});
}
var rs = fs.readFileSync('./'+pathname);
response.write(rs);
response.end();
}
if(pathInfo[pathInfo.length-1] == 'js'){ //处理js
response.writeHead(200,{'Content-Type':'text/javascript'});
var rs = fs.readFileSync('./'+pathname);
response.write(rs);
response.end();
}
if(pathname == '/'){ //请求根目录
response.write(fs.readFileSync('./index.html'));
response.end();
}else if(pathname == '/aboutus'){
if(request.method == 'GET'){
//console.log(url.parse(request.url).query); query传递的参数
//response.write(fs.readFileSync('./aboutus.html'));
var rs = fs.readFileSync('./aboutus.html','utf-8');
var params = url.parse(request.url).query;
var paramObj = querystring.parse(params);
var rs = rs.replace('<%=query%>',paramObj.id);
response.write(rs);
response.end();
}else if(request.method == 'POST'){
response.write(fs.readFileSync('./aboutus.html'));
response.end();
}
}
}).listen(8080);