引入的模塊
開(kāi)啟服務(wù),并通過(guò)url判斷需要返回的信息炊林,使用art-tempplate進(jìn)行渲染
let?html?=?tem.render(data.toString(),{????????commList??????})
res.end(html)
請(qǐng)求? ?/
請(qǐng)求 /post
其中用到服務(wù)臨時(shí)重定向
?????*??1.狀態(tài)碼設(shè)置為302
?????*??2.在響應(yīng)頭通過(guò)Location告訴客戶端往哪重定向
構(gòu)建的數(shù)據(jù)
var?commList??=?[
??{
????name:?'張三',
????message:?'啊哈哈哈哈',
????time:?'2020-04-18'
??},
??{
????name:?'張三2',
????message:?'啊哈哈哈哈2',
????time:?'2020-04-18'
??},
??{
????name:?'張三3',
????message:?'啊哈哈哈哈3',
????time:?'2020-04-18'
??},
??{
????name:?'張三4',
????message:?'啊哈哈哈哈4',
????time:?'2020-04-18'
??}
]
http.createServer((req,res)?=>?{
??let?pathObj?=?urls.parse(req.url,true)
??let?url?=?pathObj.pathname
??//?console.log(pathObj)
??if(url?===?'/')?{
????fs.readFile('./views/index.html',(err,data)?=>?{
??????if(err)?{
????????res.end('404')
????????return
??????}
??????let?html?=?tem.render(data.toString(),{
????????commList
??????})
??????res.end(html)
????})
??}else?if?(url?===?'/post')?{
????fs.readFile('./views/post.html',(err,data)?=>?{
??????if(err)?{
????????res.end('404')
????????return
??????}
??????res.end(data)
????})
??}else?if(url.indexOf('/public/')?===?0)?{
????fs.readFile(`.${url}`,(err,data)?=>?{
??????if(err)?{
????????res.end('404')
????????return
??????}
??????res.end(data)
????})
??}?else?if?(url?===?'/pl')?{
????//?console.log(pathObj.query.name)
????commList.unshift({
??????name:?pathObj.query.name,
??????message:?pathObj.query.message,
??????time:?new?Date()
????})
????//?服務(wù)端讓客戶端頁(yè)面重定向
????/**
?????*??1.狀態(tài)碼設(shè)置為302
?????*??2.在響應(yīng)頭通過(guò)Location告訴客戶端往哪重定向
?????*/
????res.statusCode?=?302
????res.setHeader('Location','/')
????res.end()
??}?else?{
????fs.readFile('./views/404.html',(err,data)?=>?{
??????if(err)?{
????????res.end('404')
????????return
??????}
??????res.end(data)
????})
??}
??//?res.end('hello?world')
}).listen(3000,()?=>?{
??console.log('開(kāi)啟成功')
})
let?html?=?tem.render(data.toString(),{
????????commList
??????})