node.js请求css、js静态资源页面不生效

产生原因:文件响应头内容类型错误

解决方案:设置对应的响应头内容类型

 

const http = require('http');
const fs = require('fs');
const path = require('path');
http.createServer((req, res) => {
    const url = req.url;
    let fpath = '';
    if(url === '/'){
        fpath = path.join(__dirname, './index.html');
        res.writeHead(200,{'Content-Type':'text/html'});
        fs.readFile(fpath, 'utf8', (err, dataStr) => {
            if (err) {
                return res.end('404 Not Found')
            }
            res.end(dataStr);
        })
    } else if(url === '/favicon.ico'){
        res.end();
    } else {
        fpath = path.join(__dirname, '.', url)
        let type = fpath.substr(fpath.lastIndexOf(".")+1,fpath.length);
        res.writeHead(200,{'Content-type':"text/"+type});
        fs.readFile(fpath, 'utf8', (err, dataStr) => {
            if (err) {
                return res.end('404 Not Found')
            }
            res.end(dataStr);
        })
    }
}).listen(3000);

  

 

posted @ 2022-03-01 16:05  PromiseOne  阅读(333)  评论(0编辑  收藏  举报