Node.js搭建web服务器时部分图片无法正常加载
// 1. 引入系统模块http
// 2. 创建网站服务器
// 3. 为网站服务器添加事件请求
// 4. 实现路由功能
const http = require('http');
const app = http.createServer();
const path = require('path');
const fs = require('fs')
const url = require('url')
app.on('request', (req, res) => {
//获取用户的绝对路径
let pathname = url.parse(req.url).pathname;
//将用户的请求路径转换为实际的服务器硬盘路径
let realPath = path.join(__dirname, 'public' + pathname);
fs.readFile(realPath, (error, result) => {
// res.end(realPath)
if (error != null) {
res.writeHeader(404, {
'content-type': 'text/html;charset=utf8' //text/plain纯本文
});
res.end('文件读取失败')
return;
}
res.end(result)
});
});
app.listen(3000);
console.log('服务器启动成功');
上述代码是使用node.js搭建web服务器,其中将realPath传入响应网页中时,路径中出现中文乱码的情况,是因为自己创建文件夹时使用了中文,网页中部分图片无法正常加载的情况也是因为部分图片的命名是中文,导致网页无法正常解析导致的。