我需要动态的返回不同的两个页面
我需要拿到这个页面字符串的时候,这里还是404,所以我该怎么办呢?
const http = require('http')
const fs = require('fs')
const path = require('path')
const server = http.createServer()
// 拿到要返回的页面内容
const content = (Path) => {
let htmlContent = '<h1>404 not found</h1>'
fs.readFile(path.join(__dirname,Path),(err,data) => {
if (err) {
return console.log(`读取${path.basename(Path)}页面失败${err.message}`)
}
// 这里是异步的,所以当我需要拿到这个字符串的时候,这里还是404,所以我该怎么办呢?
htmlContent = data.toString()
})
return htmlContent
}
content('./server/index.html')
// 自定义页面内容处理函数
const dealUrl = (url) => {
if (url === '/' || url === '/index.html') {
return content('./server/index.html')
}
if (url === '/about.html') {
return content('./server/about.html')
}
}
server.on('request', (req, res) => {
const url = req.url
const html = dealUrl(url)
res.setHeader('Content-Type', 'text/html;charset=utf-8')
res.end(html)
})
server.listen(80,() => {
console.log('listen 80 ok');
})