路由
const http = require('http')
const fs = require('fs')
http
.createServer((req, res) => {
const urlString = req.url
switch (urlString) {
case '/':
res.end('hello , 首页')
break
case '/home':
fs.readFile('./home.html', (err, content) => {
res.end(content)
})
break
case '/app.js':
fs.readFile('./app.js', (err, content) => {
res.end(content)
})
break
case '/logo.png':
fs.readFile('./logo.png', (err, content) => {
res.end(content)
})
break
default:
res.end('Page Not Found')
}
})
.listen(8081, () => {
console.log('running at localhost:8081')
})
改造
npm install mime
const http = require('http')
const fs = require('fs')
const mime = require('mime')
// http
// .createServer((req, res) => {
// const urlString = req.url
// switch (urlString) {
// case '/':
// res.end('hello , 首页')
// break
// case '/home':
// fs.readFile('./home.html', (err, content) => {
// res.end(content)
// })
// break
// case '/app.js':
// fs.readFile('./app.js', (err, content) => {
// res.end(content)
// })
// break
// case '/logo.png':
// fs.readFile('./logo.png', (err, content) => {
// res.end(content)
// })
// break
// default:
// res.end('Page Not Found')
// }
// })
const server = http.createServer((req, res) => {
const urlString = req.url
const type = mime.getType(urlString.split('.')[1])
res.writeHead(200, {
'content-type': type
})
const file = fs.readFileSync(`.${urlString}`)
res.end(file)
})
server.listen(8081, () => {
console.log('running at localhost:8081')
})