欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > 使用Node的http模块创建web服务,给客户端返回html页面时,css失效的根本原因(有助于理解http)

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

2025/3/16 17:56:44 来源:https://blog.csdn.net/m0_72642362/article/details/146287173  浏览:    关键词:使用Node的http模块创建web服务,给客户端返回html页面时,css失效的根本原因(有助于理解http)

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

这是我的源代码:

import { createServer } from '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('服务器启动成功')})

这是我的静态文件目录

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

可以发现css样式丢失

什么原因导致的呢?

我们来f12调试一下

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

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

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

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

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

那怎么解决呢?

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

修改后的代码

import { createServer } from '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('服务器启动成功')})

这个时候,页面就正常了

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词