使用Node的http模块创建web服务,给客户端返回html页面时,css失效的根本原因(有助于理解http)

server/2025/3/16 13:56:26/
htmledit_views">

最近正在尝试使用node写后端,使用node创建html" title=http>http服务的时候,碰到了这样的一个问题:

这是我的源代码:

import { createServer } from 'html" title=http>http'
import { join, dirname, extname } from 'path'
import { fileURLToPath } from 'url'
import { readFile } from 'fs'
// 创建服务器
const server = createServer()
// 定义需要运行的js文件所在目录
const __dirname = dirname(fileURLToPath(import.meta.url))
// 根据文件后缀名获取对应的Content-Type值
// const getContentType = ( filePath ) => {
//     const ext = extname(filePath).toLowerCase()
//     switch( ext) {
//         case '.html': return 'text/html;charset=utf-8'
//         case '.js': return 'application/javascript;charset=utf-8'
//         case '.css': return 'text/css;charset=utf-8'
//     }
// }
server.on('request', ( req, res ) => {const url = req.urlconst fPath = join(__dirname, '../'+url)console.log(fPath)readFile(fPath, 'utf8', ( err, dataStr ) => {if( err ) {return res.end('404 Not Found')}res.setHeader('Content-Type', 'text/html;charset=utf-8')// res.setHeader('Content-Type', getContentType(fPath))res.end(dataStr)})
})server.listen(80, () => {console.log('服务器启动成功')})

这是我的静态文件目录

html" title=http>https://i-blog.csdnimg.cn/direct/5a38664080f245748b30bb15384ba0ca.png" width="1070" />

看起来没有什么问题,但是当我在浏览器地址输入html" title=http>http://localhost/clock/index.html,因为是80端口,所以可以省略端口号

html" title=http>https://i-blog.csdnimg.cn/direct/7be4a42883ea477a8a7802dda9bff315.png" width="1919" />

可以发现css样式丢失

什么原因导致的呢?

我们来f12调试一下

html" title=http>https://i-blog.csdnimg.cn/direct/e15abe6cf0e3457eb1ae6647f665d227.png" width="1904" />

可以看到确实是请求到了三个静态文件,其中index.html的Content-Type为

text/html;charset=utf-8,没什么问题。

但是style.css的Content-Type也为text/html;charset=utf-8

html" title=http>https://i-blog.csdnimg.cn/direct/410fe1c92eda4059a9074918d91bfe2c.png" width="1919" />

这就是原因所在,响应头部错误,浏览器就不会把它解析为样式表,从而导致样式失效。

同样,index.js亦如(但是index.js脚本没有失效)

html" title=http>https://i-blog.csdnimg.cn/direct/f38420cf80394fefae8b9bff9a54aa1a.png" width="1906" />

那怎么解决呢?

我们只需要动态的根据文件后缀名设置Content-Type即可

修改后的代码

import { createServer } from 'html" title=http>http'
import { join, dirname, extname } from 'path'
import { fileURLToPath } from 'url'
import { readFile } from 'fs'
// 创建服务器
const server = createServer()
// 定义需要运行的js文件所在目录
const __dirname = dirname(fileURLToPath(import.meta.url))
// 根据文件后缀名获取对应的Content-Type值
const getContentType = ( filePath ) => {const ext = extname(filePath).toLowerCase()switch( ext) {case '.html': return 'text/html;charset=utf-8'case '.js': return 'application/javascript;charset=utf-8'case '.css': return 'text/css;charset=utf-8'}
}
server.on('request', ( req, res ) => {const url = req.urlconst fPath = join(__dirname, '../'+url)console.log(fPath)readFile(fPath, 'utf8', ( err, dataStr ) => {if( err ) {return res.end('404 Not Found')}// res.setHeader('Content-Type', 'text/html;charset=utf-8')res.setHeader('Content-Type', getContentType(fPath))res.end(dataStr)})
})server.listen(80, () => {console.log('服务器启动成功')})

这个时候,页面就正常了

html" title=http>https://i-blog.csdnimg.cn/direct/969fd0979fb1477895b52fe3fd83d966.png" width="1917" />

打开调试工具,Content-Type正常了

html" title=http>https://i-blog.csdnimg.cn/direct/f06053e4226f4543bf7cf7fb18e202db.png" width="1919" />


http://www.ppmy.cn/server/175443.html

相关文章

java智慧校园综合管理云平台源码,家校互通、物联控制、走班排课

智慧校园云平台电子班牌系统,智慧电子班牌源代码 系统主要以校园安全、智慧校园综合管理云平台为核心,以智慧班牌为学生智慧之窗,以移动管理平台、家校沟通为辅。教师—家长一学校—学生循环的无纸化管理模式及教学服务,实现多领…

【c语言数组精选代码题】

c语言数组精选代码题 四、数组4.1逆序数组4.2最值交换4.3数组排序4.4统计数字频次4.5输出矩阵4.6矩阵运算4.7找字符串索引4.8找字符串索引4.9统计字母频次4.10最长字符串🚀4.10字符串比较4.12字符串的插入🚀4.13字符串的删除🚀🚀 …

单片机ADC+NTC温度采集电路学习

文章目录 前言一、NTC是什么?二、NTC重要参数三、实际应用举例四、NTC和PTC的区别总结 前言 NTC常用来检测外部环境或者电池温度,及汽车水温传感器。 有时候电池并不内置NTC,所以需要外置NTC来采集电池温度,注意要紧贴电池&#…

深度学习 Deep Learning 第2章 线性代数

深度学习 第2章 线性代数 线性代数是深度学习的语言。 张量操作是神经网络计算的基石,矩阵乘法是前向传播的核心,范数约束模型复杂度,而生成空间理论揭示模型表达能力的本质。 本章介绍线性代数的基本内容,为进一步学习深度学习做…

Flink术语

Flink Application: 一个完整的Flink程序代码叫做一个Flink Application,其始于一个或多个Source,终于一个或多个Sink,中间由一个或者多个Operator(算子)组合对数据进行转换形成Transformation。 编写Flink代码要符合一定的流程,首…

Spring Boot实战:MySQL与Redis数据一致性深度解析与代码实战

Spring Boot实战:MySQL与Redis数据一致性深度解析与代码实战 一、数据一致性问题概述二、常见解决方案三、选择合适的解决方案四、总结 在Spring Boot开发中,MySQL作为关系型数据库,提供了强大的数据存储和查询能力;而Redis作为内…

基于 Verilog 的多路复用显示驱动设计与测试:实践与探索

在数字电路设计的学习与实践中,Verilog 语言作为硬件描述的有力工具,被广泛应用于各类电路设计场景。今天,我们将深入探讨如何运用 Verilog 实现多路复用显示驱动的设计与测试,这不仅能加深对 Verilog 语言的理解,还能提升数字电路设计的实践能力。 一、实验目的 本次实验…

解决PC串流至IPad Pro时由于分辨率不一致导致的黑边问题和鼠标滚轮反转问题

问题背景 今天在做 电脑串流ipad pro 的时候发现了2个问题: 1.ipadpro 接上鼠标后,滚轮上下反转,这个是苹果自己的模拟造成的问题,在设置里选择“触控板与鼠标”。 关闭“自然滚动”,就可以让鼠标滚轮正向滚动。 2. ipadpro 分…