【发布时间】:2021-10-17 00:37:55
【问题描述】:
我只是想知道在使用 vanilla nodejs 服务静态文件时使用大量else if 的语句是否正常:
const server = http.createServer(function(req, res) {
if (req.url == '/') {
res.writeHead(307,{'Location': '/index.html'});
res.end();
} else if (req.url == '/index.html') {
fs.readFile('index.html', function(error, data) {
if (error) {
res.writeHead(404, { 'Content-Type': 'text/html' })
res.write('<p>File could not be readed.</p>')
} else {
res.writeHead(200, { 'Content-Type': 'text/html' })
res.write(data)
}
res.end()
})} else if (req.url == "/solutions.html") {
fs.readFile('solutions.html', function(error, data) {
if (error) {
res.writeHead(404, { 'Content-Type': 'text/html'})
res.write('<p>File could not be readed.</p>')
} else {
res.writeHead(200, { 'Content-Type': 'text/html'})
res.write(data)
}
res.end()
})} else if (req.url == "/solutions/antoher-subpage.html") {
res.writeHead(200, {'Content-Type': 'text/html'})
res.write('0.1')
res.end()
}
上面的模型是我用来提供静态文件的模型,但是随着页面的增长我需要为我想要添加的每个页面添加一个else if。
这正常吗?有没有办法通过使用原始 Node JS 来解决这个问题?如果没有,你会推荐什么?
谢谢。
【问题讨论】:
标签: node.js http if-statement