使用NodeJs實現頁面的跳轉
1 創建testApp.js:
var http=require('http');
var fs=require('fs');
var server =http.createServer();
server.listen(8080,function(){
console.log("Server is rining port 8080");
});
//請求回調函數
var handRequest=function (req,res){
console.log('當前的請求是:'+req.url);
// response.write('hello');
// response.write('world');
//response.writeHead(響應狀態碼,響應頭對象)
var url=req.url;
if(url=="/login"){
res.writeHead(200,{
'Content-Type':'text/html'
});
fs.readFile('index.html','utf8',function(err,data){
if(err){
throw err;
}
res.end(data);
});
}else{
res.writeHead(200,{
'Content-Type':'text/html'
});
fs.readFile('404.html','utf8',function(err,data){
if(err){
throw err;
}
res.end(data);
});
}
//發送完數據後結束響應
//res.end('404 NotFound');
};
//任何請求都會觸發該事件
server.on('request',handRequest);
2 創建index.html和404.html
3 最後運行testApp.js,命令 node testApp.js:
成功界面: