之前培训canvas的时候,看到他们用自己搭建的服务器玩得挺6的,于是自己上网找了一篇文章,自己学着用node去搭建了一个服务器,下面是原文章:
这是我自己搭建的服务器:
首先看看文件目录:
文件目录很简单,3个页面和一个js文件,服务器实现的代码在serve.js里面
let http = require('http')
// 创建http服务器
let server = http.createServer(function(req,res){
//设置响应头
res.writeHead(200,{
'content-type':'text/html'
})
//设置响应数据
res.write('hello world')
// 一定要添加,不然响应不会结束
res.end()
})
//设置服务器端口
server.listen(2021,function(){
console.log( "2021端口已开启" )
})
这样本地浏览器打开http://localhost:2021就可以获得响应的数据hello world。
通常我们是相应的某个HTML文件,那怎么办呢?这时我们引入一个fs模块用来读取文件流
let http = require('http')
let fs=require('fs')
// 创建http服务器
let server = http.createServer(function(req,res){
//设置响应头
res.writeHead(200,{
'content-type':'text/html'
})
// 读取文件数据
let data=fs.readFileSync("./index.html")
//设置响应数据
res.write(data)
res.end()
})
这时候读取的是index.html的内容
那如果我们想要根据路由的不同去读取不同文件里面的内容那又该怎么写呢
let http = require('http')
let fs=require('fs')
// 引入URL 代码块
let url = require('url')
let server = http.createServer()
server.on ("request", (req,res)=>{
// 获得请求方式
let method=req.method;
// 格式化请求链接
// let newUrl = url.parse(req.url)
// 使用对象. 获得关键信息pathname
let newPath = url.parse(req.url).pathname
let data=''
res.writeHead(200,{
"content-type":"text/html;charset=utf8"
})
if(newPath=="/index2"){
data=fs.readFileSync("./index2.html")
}else if(newPath=="/index3"){
data=fs.readFileSync("./index3.html")
}else if(newPath=="/index"){
data=fs.readFileSync("./index.html")
}else {
res.writeHead(404, {
"content-Type": "text/html;charset=utf8"
})
res.end("<h1>你要找的页面走丢了</h1>")
}
// res.write(data)
res.end(data)
})
//设置服务器端口
server.listen(2021,function(){
console.log( "2021端口已开启" )
})
其实大致的思路就是获取request中的路径pathname,然后再进行一一匹配,去加载对应的数据,再返回,同时也可以获得相应的请求方式。
新手分享,希望这边文章对你们有帮助