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

时间:2015-03-01 14:41:15

标签: javascript node.js

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

The 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!");

终端

enter image description here

Chrome控制台

enter image description here

enter image description here

enter image description here

任何人都可以帮助我或告诉我我做错了什么? 我只是想使用nodejs not express或者谢谢你。

1 个答案:

答案 0 :(得分:1)

问题是您尝试使用根位置打开文件。 request.url返回/css/init.css,您正在从同一位置读取文件。用.作为前缀,或者从脚本位置解析相对路径。