您的位置:首页 > Web前端 > Node.js

Node.js_路由机制_静态资源文件的使用(2)

2019-04-08 17:17 435 查看
  • Node.js路由机制_静态资源的使用
//day1/07-01.js
var http=require("http");
var fs=require("fs");
http.createServer(function(req,res){
if(req.url=="/haha.html"){
fs.readFile("./public/b.html",function(err,data){
res.end(data);
});
}else if(req.url=="/css.css"){
fs.readFile("./public/css.css",function(err,data){
res.end(data);
});
}else if(req.url=="/0.jpg"){
fs.readFile("./public/0.jpg",function(err,data){
res.end(data);
});
}else if(req.url=="/s.js"){
fs.readFile("./public/s.js",function(err,data){
res.end(data);
});
}
else{
res.end("没有这个页面");
}
}).listen(3000);
console.log("Server start at 3000 port");
<!-- b.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css.css" />
<link rel="stylesheet" href="index.css" />
</head>
<body>
<h1>我是b.html</h1>
<p>
<img src="0.jpg" alt="">
</p>
<script type="text/javas
1d25c
cript" src="s.js"></script>
</body>
</html>

Node.js每当使用一个真实的文件,就需要为其创建一个路由,以便文件能够被正确的被http请求读取。

  • url模块、path模块、querystring模块

如果一个URL比较完整,包括querystring部分(就是GET请求查询字符串部分)、hash部分:

http://127.0.0.1:3000/b.html?id=123&name=小明&age=18#123

此时req.url是: /b.html?id=123 ,hash部分不包括。

var http=require("http");
var fs=require("fs");
var url=require("url");
http.createServer(function(req,res){
//转为对象
var urljson=url.parse(req.url);
console.log(urljson);
res.end("");
}).listen(3000,"127.0.0.1");
console.log("server start at 3000 port");

var http=require("http");
var fs=require("fs");
var url=require("url");
http.createServer(function(req,res){
//转为对象 true表示将query部分转成对象
var urljson=url.parse(req.url,true);
console.log(urljson);
res.end("");
}).listen(3000,"127.0.0.1");
console.log("server start at 3000 port");

//day1\08.js
var http=require("http");
var fs=require("fs");
var url=require("url");
var path=require("path");
http.createServer(function(req,res){
//转为对象 true表示将query部分转成对象
var urljson=url.parse(req.url,true);
//得到文件路径
var pathname=urljson.pathname;
//得到拓展名
var extname=path.extname(pathname);
console.log(pathname);
console.log(extname);
res.end("");
}).listen(3000,"127.0.0.1");
console.log("server start at 3000 port");

//day1\08.js
var http=require("http");
var fs=require("fs");
var url=require("url");
var path=require("path");
var querystring=require("querystring");
http.createServer(function(req,res){
//转为对象 true表示将query部分转成对象
//var urljson=url.parse(req.url,true);
var urljson=url.parse(req.url);
//得到文件路径
var pathname=urljson.pathname;
//得到拓展名
var extname=path.extname(pathname);
//得到查询字符串
var qs=urljson.query;
//转为查询对象,和url.parse加上true非常类似。
var qsjson=querystring.parse(qs);
console.log(pathname);
console.log(extname);
// console.log(qs);
console.log(qsjson);
res.end("");
}).listen(3000,"127.0.0.1");
console.log("server start at 3000 port");

querystring模块和path模块都是服务于url的。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: