const http = require('http'); const app = http.createServer(); const url = require('url'); const path = require('path'); const fs = require('fs'); const mime = require('mime'); app.on('request', (req, res) => { // 处理请求 let pathname = url.parse(req.url).pathname; pathname = pathname == '/' ? '/default.html' : pathname; let realPath = path.join(__dirname, 'public' + pathname); let type = mime.getType(realPath); fs.readFile(realPath, (error, result) => { if (error != null) { res.writeHead(404, { 'content-type': 'text/html;charset=utf8' }); res.end('文件读取失败'); } else { res.writeHead(200, { 'content-type': type }); res.end(result); }; }); // 监听 3000 端口 app.listen(3000); console.log('服务器已启动,监听 3000 端口,请访问 localhost:3000');检查这段代码的错误
时间: 2024-03-27 16:41:16 浏览: 58
这段代码可能存在一个错误,即在读取文件成功时的 else 分支中,应该在最后加上一个分号。正确的代码如下:
```
const http = require('http');
const app = http.createServer();
const url = require('url');
const path = require('path');
const fs = require('fs');
const mime = require('mime');
app.on('request', (req, res) => {
// 处理请求
let pathname = url.parse(req.url).pathname;
pathname = pathname == '/' ? '/default.html' : pathname;
let realPath = path.join(__dirname, 'public' + pathname);
let type = mime.getType(realPath);
fs.readFile(realPath, (error, result) => {
if (error != null) {
res.writeHead(404, { 'content-type': 'text/html;charset=utf8' });
res.end('文件读取失败');
} else {
res.writeHead(200, {
'content-type': type
});
res.end(result);
}
});
});
// 监听 3000 端口
app.listen(3000);
console.log('服务器已启动,监听 3000 端口,请访问 localhost:3000');
```
阅读全文