Node.js – 资源解释为脚本但使用MIME类型text / plain传输

前端之家收集整理的这篇文章主要介绍了Node.js – 资源解释为脚本但使用MIME类型text / plain传输前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
首先:我没有使用Express.

有了这个,当我加载我的index.html文件时,它递归readFile每个附加的文件,如我的CSS和JS页面.但它总是在我的检查器(Chrome)中返回此错误

Resource interpreted as Script but transferred with MIME type text/plain

我完全不知道为什么会这样做.这是我的代码

var http = require('http');
var querystring = require('querystring');
var fs = require('fs');
var url = require('url');

function route(handle,pathname,response,request){
console.log("About to route a request for " + pathname);

if (typeof handle[pathname] === "function"){        
    handle[pathname](response,request);
    } else {

    var file_path = "";

    // parses the url request for a file and pulls the pathname
    var url_request = url.parse(request.url).pathname;      
    var tmp  = url_request.lastIndexOf(".");
    var extension  = url_request.substring((tmp + 1));

    file_path = url_request.replace("/","");

    //load needed pages and static files
    fs.readFile(file_path,function (error,contents){
        if(error){
          console.log('DIE!');
          console.log(error);
          response.writeHeader(500,{"Content-Type": "text/html"});  
          response.end("<h1>FS READ FILE ERROR: Internal Server Error!</h1>");    
        }
        else{ 
          console.log('SUCCESS!');
          // set content type
          if (extension === 'html') response.writeHeader(200,{"Content-Type": 'text/html'});
          else if (extension === 'htm') response.writeHeader(200,{"Content-Type": 'text/html'});
          else if (extension === 'css') response.writeHeader(200,{"Content-Type": 'text/css'});
          else if (extension === 'js') response.writeHeader(200,{"Content-Type": 'text/javascript'});
          else if (extension === 'png') response.writeHeader(200,{"Content-Type": 'image/png'});
          else if (extension === 'jpg') response.writeHeader(200,{"Content-Type": 'image/jpg'});
          else if (extension === 'jpeg') response.writeHeader(200,{"Content-Type": 'image/jpeg'});
          else { console.log("NO CORRECT EXTENSION")};
            console.log(extension);
            response.end(contents);
        }

        response.end();  
    });
    response.end();
}
}

exports.route = route;

我怎样才能解决这个问题?这已经阻止了我的项目.

注意:这是我在这里谈到的早期问题的进展:Node.js incorrect path problems

解决方法

尝试注释掉最后一个响应.不要以为你需要它.
response.end();  
    });
    // response.end();
   }
   exports.route = route;

我怀疑response.end是在fs.readfile回调内部有时间执行之前立即调用的,可能会关闭服务器上的标题而没有给出正确的标题“Content-Type”:’text / javascript’一个机会要发送..

试过你的代码,为我工作..

猜你在找的Node.js相关文章