如何在无Express的Node.js项目中使用多个外部CSS文件?
问题修复方案
你的代码里存在赋值操作代替相等比较的错误,导致所有CSS请求都返回style.css,具体问题出在这两处:
else if (req.url = '/style.css')else if (req.url = '/about.css')
这里应该用**严格相等运算符===**来判断请求路径,而不是赋值运算符=。赋值操作会直接修改req.url的值,使得后续的about.css判断永远不会被执行。
修正后的完整代码如下:
const http = require('http') const { readFileSync } = require('fs') const server = http.createServer(function (req, res) { if (req.url === '/') { let data = readFileSync('./home.html') res.write(data) res.end() } else if (req.url === '/about') { let data = readFileSync('./about.html') res.write(data) res.end() } else if (req.url === '/fish.png') { const image = readFileSync('fish.png') res.writeHead(200, { 'Content-Type': 'image/png' }) res.write(image) res.end() } else if (req.url === '/style.css') { // 替换为严格相等判断 const css = readFileSync('./style.css') res.writeHead(200, { 'Content-Type': 'text/css' }) res.write(css) res.end() } else if (req.url === '/about.css') { // 替换为严格相等判断 const css = readFileSync('./about.css') res.writeHead(200, { 'Content-Type': 'text/css' }) res.write(css) res.end() } else { res.end('something is wrong with the server') } }) server.listen(8080, () => console.log('server is running on 8080'))
额外需要确认:
home.html中正确引用了<link rel="stylesheet" href="/style.css">about.html中正确引用了<link rel="stylesheet" href="/about.css">
内容的提问来源于stack exchange,提问作者sOhan chaudhuree
相关产品推荐
相关产品推荐

