中级实作学的东西。作业做的是一个电影推荐网站,负责的部分是后台管理页面。已经忘记怎么做的了。
服务器端
使用Nodejs + http 创建web服务器
1.导入模块
2.创建服务器,设置监听端口
3.找到文件路径
4.读取文件到前端
5.结束请求
#server.js
//使用Nodejs + http 创建web服务器
var http = require("http"); //http模块,用来创建服务器
var fs = require("fs"); //fs模块文件系统,读取文件写到前端
var url = require("url"); //解析网址路径模块,找到文件位置
//配置一个服务器
http.createServer(function (request, response) {
var pathname = url.parse(request.url).pathname;//parse显示已被废弃
console.log(url.parse(request.url))
/*Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/server.html',
path: '/server.html',
href: '/server.html'
AND
pathname: '/test.css',
path: '/test.css',
href: '/test.css'
}*/
console.log("Request for " + pathname + " received.");
//Request for /server.html received.
//Request for /test.css received.
var firstDir = pathname && pathname.split('.')[1]; //文件类型 html
var ContentType = {
'Content-Type': 'text/html'
};
if (firstDir == 'css') {
ContentType = {
'Content-Type': 'text/css'
};
}
fs.readFile(pathname.substr(1), function (err, data) {//substr显示已被废弃
console.log(pathname.substr(1)) //test/test.html
if (err) {
console.log(err);
//HTTP 状态码 404 : NOT FOUND
//Content Type:text/plain
response.writeHead(404, {
'Content-Type': 'text/html'
});
} else {
//HTTP 状态码 200 : OK
//Content Type:text/plain
response.writeHead(200, ContentType);
//写会回相应内容
response.write(data.toString());
}
//发送响应数据,结束请求,否则前端会一直处于等待状态
response.end();
});
}).listen(8081); //监听端口
console.log('Server running at http://127.0.0.1:8081/');
谢谢博主勤奋者是天才Nodejs搭建web服务器_技术宅男-CSDN博客_nodejs搭建web服务器,在其分享的代码基础上,我补充了一些自己不熟悉的点。
#server.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/test.css">
</head>
<body>
<h1 class="hello">hello!</h1>
</body>
</html>
#test.css
h1{
color: red;
}
结果
substr和parse显示已被废弃,还没做了解。
解析一下其他链接试试看。
console.log(url.parse("https://blog.csdn.net/weixin_46106424?type=blog"))
/*Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'blog.csdn.net',
port: null,
hostname: 'blog.csdn.net',
hash: null,
search: null,
query: null,
pathname: '/XIAO_YuBaby/article/details/103190255',
path: '/XIAO_YuBaby/article/details/103190255',
href: 'https://blog.csdn.net/XIAO_YuBaby/article/details/103190255'
}*/
使用Nodejs + express创建web服务器
——————被MaskRCNN截胡了,不想放在草稿箱,先发,晚点再继续更新———————