如何使用nodejs加载js和css文件

我很难用nodejs加载css和js文件,这是我到目前为止

Js

/** Install nodeJs server the easy way * * $ npm install http-server -g // install http server * globally * $ cd MyApp // navigate to the app's root folder * $ http-server //run the server * **/ console.log("Welcome to sandy server"); //Module requires var http = require("http"), //load http node module fs = require("fs"), //load file system path = require('path'), url = require('url'), data = require('./data'); //load file index.js in sub-folder data //Object "MIMETYPES" var MIMETYPES = { html: "text/html; charset=utf-8", jpeg: "image/jpeg", jpg: "image/jpeg", png: "image/png", js: "text/javascript", css: "text/css" }, PORT = 8080; http.createServer(function (request, response){ //Returns a new instance of http.Server. console.log("request well recieved",request.url); var listener = function (error, contentType){ if(error){ console.log('DIE!', error); if(contentType !== "undefined"){ response.writeHeader(500, {"Content-Type": contentType}); }else{ response.writeHeader(500, {"Content-Type": "text/plain"}); } response.end("<h1>FS READ FILE ERROR: Internal Server Error!</h1>"); } }; var fileArray = request.url.split('.', 2), filenameExtension = fileArray[1]; if( MIMETYPES.hasOwnProperty(filenameExtension) ){ console.log("MIMETYPES::: ",MIMETYPES[filenameExtension]); fs.readFile(request.url, function (error, fileContent){ listener(error,MIMETYPES[filenameExtension]); response.writeHead(200, {'Content-Type': MIMETYPES[filenameExtension]}); response.write(fileContent); response.end(); }); } else{ console.log("::: Not in MIMETYPES ::: "); fs.readFile("./spa.html", function (error, fileContent){ listener(error); response.writeHead(200, {'Content-Type': MIMETYPES["html"]}); response.write(fileContent); response.end(); }); } console.log("end of the request"); }).listen(PORT, '127.0.0.1');//run the server on port console.log("Server running at http://127.0.0.1:" + PORT + "/ see you next time!"); 

终奌站

在这里输入图像描述

Chrome控制台

在这里输入图像描述

在这里输入图像描述

在这里输入图像描述

有人可以帮我吗?或者告诉我我做错了什么? 我只是想使用nodejs不表示或感谢你。

问题是您正在尝试使用根位置打开文件。 request.url返回/css/init.css ,你正在从同一个位置读取一个文件。 加上它. 或从脚本位置parsing相对path。