1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| const http = require('http'); const fs = require('fs'); const server = http.createServer(); server.on('request', (req, res) => { const url = req.url; if (url === '/') { fs.readFile('./resource/index.html', (error, data) => { if (error) { res.setHeader('Content-Type', 'text/plain,charset=utf-8'); res.end('文件读取失败,请稍后再试'); } else { res.setHeader('Content-Type', 'text/html,charset=utf-8'); res.end(data); }; }); } else if (url === '/images') { fs.readFile('./resource/images/3.jpg', (error, data) => { if (error) { res.setHeader('Content-Type', ' text/plain,charset=utf-8'); res.end('图片读取失败,请稍后再试'); } else { res.setHeader('Content-Type', ' image/jpeg'); res.end(data); }; }); }
}); server.listen(3000, () => { console.log('服务器启动成功,可以通过 http://127.0.0.1:3000/ 来访问');
})
|