Node.js全栈指南:认识MIME和HTTP
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                在Node.js中,MIME类型用于标识发送给客户端内容的数据类型。HTTP协议依赖MIME类型来正确处理和显示内容。
以下是如何在Node.js中设置HTTP服务器,并正确地发送MIME类型的示例代码:
const http = require('http');
const fs = require('fs');
const path = require('path');
 
http.createServer((req, res) => {
    // 设置默认的HTTP头部
    res.writeHead(200, {'Content-Type': 'text/html'});
 
    // 读取文件并发送响应
    const filePath = path.join(__dirname, 'index.html');
    fs.readFile(filePath, (err, data) => {
        if (err) {
            res.writeHead(404, {'Content-Type': 'text/html'});
            res.write('<html><body><h1>404 Not Found</h1></body></html>');
            return res.end();
        }
        res.write(data); // 发送HTML文件内容
        res.end();
    });
}).listen(8080);
 
console.log('Server is running at http://localhost:8080');在这个例子中,我们创建了一个简单的HTTP服务器,监听8080端口。对于请求index.html的响应,我们设置了正确的MIME类型text/html,这样浏览器就会将接收到的内容作为HTML来解析。如果文件不存在,我们会返回一个自定义的404错误页面,并再次设置正确的MIME类型。
评论已关闭