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

发布于:2025-03-16 ⋅ 阅读:(18) ⋅ 点赞:(0)

最近正在尝试使用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.url
    const 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.url
    const 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正常了


网站公告

今日签到

点亮在社区的每一天
去签到