1.http模块应用实例
node自带有很多模块,其中包括http模块,使用之前需要reuqire加载进来
http.js:
var http = require("http");
//req:请求
//res:response响应
var server = http.createServer(function(req,res) {//创建服务器对象,包含回调函数及两个参数req和res
console.log(req.url);//返回请求地址
//返回页面的头文件,设置编码等(防止可能返回的乱码)
res.writeHead(200,{"Conten-type":"text/htmlcharset=utf-8"})
//res.write("响应的内容");
res.end("<a href=''###'>响应结束</a>");
})
server.listen(8080,function () {
console.log("开启成功:http://local:8080");
})
在终端运行node 3.http,显示开启成功:http://localhost:8080,打开网页显示res.end的结果,若修改了代码需要重启服务器
如果我们在浏览器地址栏的http://localhost:8080后面加上/等符号回车,可以看到c在控制台打印出输入的相应的符号,由此可以可以用输入的/地址来判断用户要访问的页面来给它显示需要的页面
那么js文件可以这样写:
var http = require("http");
/*
*req:request请求
*res:response响应
*res.writeHead设置请求头
* */
var server = http.createServer(function(req,res) {
console.log(req.url);
if(req.url=="/" || req.url=="/index"){//访问主页用斜杠或者/index
res.writeHead(200,{"Content-type":"text/html;charset=utf-8"});
res.end("首页");
}else if(req.url=="/login"){//访问login页面
res.writeHead(200,{"Content-type":"text/html;charset=utf-8"});
res.end("登陆页");
}else{//若用户访问的页面不存在,返回404结果
res.writeHead(404,{"Content-type":"text/html;charset=utf-8"});
res.end("没有找到该页面");
}
})
server.listen(8080,function () {
console.log("开启成功:http://localhost:8080");
})
重启服务器,浏览器访问localhost:8080,默认显示主页返回结果“首页”,地址后面加上/login返回“登陆”,尝试访问其他页面返回“404,没有找到该页面”
2.url模块应用实例
node里面的url模块用于处理地址,根据地址获取请求信息,比如发送姓名和年龄:
var http = require("http");
var url = require("url");
var server = http.createServer(function(req,res) {
// url.parse第二个参数bol 如果true返回对象的query属性会转为json对象
var urlObj = url.parse(req.url,true);
console.log(urlObj);//终端返回请求的地址信息
res.end("姓名:"+urlObj.query.name+";年龄:"+urlObj.query.age);
})
server.listen(8080,function () {
console.log("开启成功:http://localhost:8080");
})
测试时在终端开始服务器,在浏览器地址栏输入http://localhost:8080/?name=abc&age=12,在浏览器中就会返回“姓名:abc;年龄:12”信息。此方式为get请求方式,post请求方式如下:index.html包含form表单文件:
<form action="http://localhost:8080" method="post">
<input type="text" name="user">
<input type="text"name="pwd">
<input type="submit">
</form>
js文件:
var http = require("http");
var fs = require("fs");
var server =http.createServer(function(req,res){
//获取POST传送的数据
req.on("data",function (data) {
console.log(data.toString());
})
var url = req.url;
// "/" "index.html"
if(url=="/"){
url = "/index.html";
}
var isFile = false;
//判断访问的地址文件是否存在
var bol = fs.existsSync("www"+url);
if(bol){
console.log("www"+url)
var stat = fs.lstatSync("www"+url);
var isFile = stat.isFile()
}
if(isFile){
// var rs = fs.createReadStream("www"+url);
// rs.pipe(res);
var con = fs.readFileSync("www"+url);
res.end(con);
}else{
res.writeHead(404,{"Content-type":"text/html;charset=utf-8"})
res.end("没有找到该页面");
}
});
server.listen(8080,function(){
console.log('开启成功:http://localhost:8080')
});