服务器在/about或/etc处崩溃,但在if和else块中工作正常。
请让我知道我在这里走错了。
const fs = require('fs')
const http = require('http');
const port = process.env.PORT || 3000 ;
const server = http.createServer((req, res )=> {
res.setHeader('Content-Type', 'text\html' )
if (req.url == '/') {
res.statusCode = 200;
res.end('<h1>Hello this is home page</h1>')
}
else if (req.url == '/about') {
res.statusCode = 200;
const data = fs.readFile('./index.js')
res.end(data.toString());
}
else {
res.statusCode = 404;
res.end('<h1>Page Not Found</h1>')
}
});
server.listen(port, ()=> {
console.log(`Server is listening on port ${port}`);
})
1条答案
按热度按时间62lalag41#
readFile
函数是异步的,它接受回调。应提供回调或使用readFileSync()
。回调示例:
readFileSync()
示例: