【问题标题】:Javascript and CSS don't work in node serverJavascript 和 CSS 在节点服务器中不起作用
【发布时间】:2020-07-30 15:52:23
【问题描述】:

所以我正在尝试使用节点服务器制作一个网络应用程序。我遇到了一个问题,即 CSS、Javascript 在将它们与 src 或 . 链接时不起作用。

我可以拥有css和javascript的唯一方法是直接将它放在脚本和样式参数中,但这似乎并不实用

它拉出的错误显示了一个url: 127.0.0.1/home.js

为什么会发生这种情况,有解决办法吗?

这里是代码

const fetch = require('node-fetch');
const fs = require("fs");
const http = require("http");
const url = require("url");

const server = http.createServer((req, res) => {

    // get URL
    const pathName = url.parse(req.url, true).pathname;

    console.log(pathName);
    // create split pathName
    const pathSplit = pathName.split("/");
    pathSplit.shift();

    // HOME PATH
    if(pathName === "/home" || pathName === "/"){
        // Get HTML data
        const data = renderHome();

        res.writeHead(200, {"content-type": "text/html"});
        
        fs.readFile(`${__dirname}/templates/template-basic.html`, "utf-8", (err, data) => {

            fs.readFile(`${__dirname}/templates/template-battlepass.html`, "utf-8", (err, d) => {
                let output = data.replace("{%CONTAINER%}", d);
                res.end(output);
            });
        });
        
    }
    
    // ITEM SHOP PATH
    else if(pathName === "/itemShop") {
        // Get HTML data
        const data = renderItemShop();
        
        res.writeHead(200, {"content-type": "text/html"});
        res.end("This is the item shop page");
    }
    
    // TOURNAMENTS PATH
    else if(pathName === "/tournaments") {
        // Get HTML data
        const data = renderTournaments();

        res.writeHead(200, {"content-type": "text/html"});
        res.end("this is the tournaments page");
    }
    
    // ITEMS PATH
    else if(pathSplit[0] === "items") {

        // List all the items for the page
        const itemsPages = ["backpacks", "contrails", "emotes", "gliders", "skins", "pickaxes", "wraps"];
        let itemConfirm = false;
        
        // If URL has been found, change itemConfirm to true
        for(let i = 0; i < itemsPages.length; i++){
            if(itemsPages[i] === pathSplit[1]){
                // Get HTML data
                const data = renderItems(pathSplit[1]);
                
                res.writeHead(200, {"content-type": "text/html"});
                res.end(`This is the page for ${pathSplit[1]} in items`);
                itemConfirm = true;
            }
        };

        // If itemConfirm is false, no url found
        if(itemConfirm === false) {
            res.writeHead(404, {"content-type": "text/html"});
            res.end(`No URL found for ${pathSplit[1]} in items`);
        };
    }

    // JAVASCRIPT

    // NO URL FOUND PATH: 404
    else{
        res.writeHead(404, {"content-type": "text/html"});
        res.end("could not find URL");
    }
});
server.listen(1337, "127.0.0.1", () => {
    console.log("listening for reqs now");
});

【问题讨论】:

标签: javascript css node.js url webserver


【解决方案1】:

我创建了一个简单的服务器,它可以使用 mime-types 库为任何类型的文件提供服务。我的基本 http 服务器是这样工作的:

const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types'); //Creates the appropriate headerType based on the extension

http.createServer(function (request, response) {
  let fileName = path.basename(request.url) || 'index.html' //so that the homepage uses index.html
  filePathPart = path.dirname(request.url).slice(1) + "/" + fileName
  filePath = "public/" + filePathPart //I store my files in public/js/ or public/css/
  console.log(filePath) //just to check if I got the correct files
  mimeType = mime.contentType(fileName)
  getFile(response, mimeType, filePath)
}).listen(8080);


//I wrote a function to write all the responses the server gives, with this I don't need to expect a specific number of inputs, I can load any number of js/css files or even other html pages.
function getFile(response, mimeType, filePath) {
  fs.readFile(filePath, function (err, contents) {
    response.writeHead(200, { "Content-Type": mimeType });
    response.end(contents);
  })
}

【讨论】:

  • 有没有办法使用 url if/else 语句提供静态文件?
  • 您可以在 getFile 函数中执行此操作,但实际上您并不需要它,因为该服务器将从 localhost:8080 和任何后续页面提供每个文件。所以基本上它是做什么的,它接收请求的路径,设置 mime 类型并呈现响应。你真的不需要任何进一步的逻辑。
  • 是的,我在 youtube 上看到了这个。它看起来确实有点复杂,所以我需要进一步研究。
猜你喜欢
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
相关资源
最近更新 更多