在nodejs中请求url=/about时服务器崩溃

3vpjnl9f  于 2023-03-17  发布在  Node.js
关注(0)|答案(1)|浏览(123)

服务器在/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}`);
})
62lalag4

62lalag41#

readFile函数是异步的,它接受回调。应提供回调或使用readFileSync()
回调示例:

res.statusCode = 200;
const data = fs.readFile('./index.js', 'utf8', (err, data) => {
    res.end(data.toString());
});

readFileSync()示例:

res.statusCode = 200;
const data = fs.readFileSync('./index.js', 'utf8');
res.end(data.toString());

相关问题