1. http模块
2. url模块
var http = require("http");
var url=require("url");
var server = http.createServer(function(req,res){
//url.parse()可以将一个完整的URL地址,分为很多部分:host、port、pathname、path、query
var pathname=url.parse(req.url).pathname;
url.parse()第二个参数为true,就可以将所有的查询变为对象,直接打点调用
var query=url.parse(req.url,true).query;
var age=query.age;
console.log("pathname:"+pathname);
console.log("age:"+age);
res.end();
});
server.listen(3000,"127.0.0.1");
3.设置路由req.url
var http = require("http");
var server = http.createServer(function(req,res){
//得到地址栏的url
var userurl = req.url;
res.writeHead(200,{"Content-type":"text/html;charset=utf-8"});
if (userurl.substr(0,9) == "/student/") {
var studentid=userurl.substr(9);
if (/^\d{10}$/.test(studentid)) {
res.end("您要查询学生信息,id为"+studentid);
} else {
res.end("您输入的学生学号不正确");
}
} else if (userurl.substr(0,9) == "/teacher/") {
var teacherid=userurl.substr(9);
if (/^\d{6}$/.test(teacherid)) {
res.end("您要查询老师信息,id为"+teacherid);
}else{
res.end("您输入的老师学号不正确");
}
}else{
res.end("请检查url");
}
});
server.listen(3000,"127.0.0.1");