How can I include css files using node, express, and ejs?

前端 未结 11 849
执念已碎
执念已碎 2020-12-01 01:37

I\'m trying to follow the instructions to https://stackoverflow.com/a/18633827/2063561, but I still can\'t get my styles.css to load.

From app.js

ap         


        
11条回答
  •  盖世英雄少女心
    2020-12-01 02:29

    For NodeJS I would get the file name from the res.url, write the header for the file by getting the extension of the file with path.extname, create a read stream for the file, and pipe the response.

    const http = require('http');
    const fs = require('fs');
    const path = require('path');
    const port = process.env.PORT || 3000;
    
    const server = http.createServer((req, res) => {
        let filePath = path.join(
            __dirname,
            "public",
            req.url === "/" ? "index.html" : req.url
        );
    
        let extName = path.extname(filePath);
        let contentType = 'text/html';
    
        switch (extName) {
            case '.css':
                contentType = 'text/css';
                break;
            case '.js':
                contentType = 'text/javascript';
                break;
            case '.json':
                contentType = 'application/json';
                break;
            case '.png':
                contentType = 'image/png';
                break;
            case '.jpg':
                contentType = 'image/jpg';
                break;
        }
    
        console.log(`File path: ${filePath}`);
        console.log(`Content-Type: ${contentType}`)
    
        res.writeHead(200, {'Content-Type': contentType});
    
        const readStream = fs.createReadStream(filePath);
        readStream.pipe(res);
    });
    
    server.listen(port, (err) => {
        if (err) {
            console.log(`Error: ${err}`)
        } else {
            console.log(`Server listening at port ${port}...`);
        }
    });
    

提交回复
热议问题