【问题标题】:Simple Nodejs web server always sends text/plain css and js files简单的 Nodejs Web 服务器总是发送文本/纯 css 和 js 文件
【发布时间】:2014-01-12 02:57:01
【问题描述】:

我在Nodejs 中创建一个简单的网络服务器时遇到了一个奇怪的问题。 http 服务器运行良好,可以正常接受请求和响应。但是,出于某种原因,它总是希望为所有内容发送 content-type: 或 text/plain。例如,.js 和.css 文件始终以text/plain 的形式出现,而它们通常应以text/css 或application/javascript 的形式发送。 Chrome,我用来测试的浏览器,总是抱怨资源的 MIME 类型:

Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:3000/test.css".

Resource interpreted as Script but transferred with MIME type text/plain: "http://localhost:3000/test-client.js".

这最终意味着css 永远不会应用于页面。我添加了一些日志记录,看起来 http 响应正在发送正确的 MIME 类型。

我已经创建了我正在做的事情的准系统版本。希望有人能指出我编码的缺陷:

test.js

var http = require('http'),
    fs = require('fs'),
    url = require('url'),
    path = require('path');
var contentTypes = {
    '.html': 'text/html',
    '.css': "text/css",
    '.js': 'application/javascript'
};
http.createServer(function(request, response) {
    // get file based on pathname
    var uri = url.parse(request.url).pathname,
        filename = path.join(__dirname, uri);
    fs.exists(filename, function(exists) {
        // if root directory, append test.html
        if (fs.statSync(filename).isDirectory()) {
            filename += 'test.html';
        }
        // figure out MIME type by file ext
        var contentType = contentTypes[path.extname(filename)];
        fs.readFile(filename, function(err, file) {
            // errors?
            if (err) {
                response.writeHead(404, {'Content-type:': 'text/plain'});
                response.write(err + "\n");
                response.end();
            } else {
                console.log('MIME TYPE for: ', filename , contentType);
                response.setHeader('Content-Type:', contentType);
                response.writeHead(200);
                response.write(file);
                response.end();
            }
        });
    });
}).listen(3000, function(){
    console.log("server started and listening on port 3000");
});

test.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="test.css" type="text/css" />
    </head>
    <body>
        <h1>Test</h1>
        <div id="test"></div>
        <script type="text/javascript" src="test-client.js"></script>
    </body>
</html>

test.css

h1 {
    color: red;
}

test-client.js

var div = document.getElementById('test');
div.innerHTML = 'test client ran successfully';

【问题讨论】:

  • 设置标题时,您并没有真正做对。据我所知,您不应该使用response.setHeader,而是使用response.writeHead(200,{'Content-Type':'contentType'});,并且在错误处理程序中,对于writeHead 上的选项,您使用{'Content-Type:','something-or/other'},但不应该是@987654340 @ 在Content-Type 之后:应该只是Content-Type
  • 感谢您希望将问题标记为已解决 - 但是,在 Stack Overflow 上,标记很好 :)。

标签: javascript css node.js http google-chrome


【解决方案1】:

我遇到了同样的问题,但是我的问题略有不同。我最初是使用这种方法来设置Content_Type:

res.writeHead(200, { 'Content_Type': contentType });

用以下内容替换后,错误消失了:

res.setHeader('Content-Type',contentType)

【讨论】:

    【解决方案2】:

    并且你必须让fs.readFile被一个闭包包裹,否则一些文件(尤其是最后一个文件)会被多次读取,而另一些则根本不会被读取。并且contentType 不会按照您的意愿设置。这是因为fs.readFile 使用的回调策略。当 html 文件只加载一个外部文件时,问题不会出现,但是当外部文件(css,js,png)加载多个时,它会像我上面指出的那样出现。 (我无法使用我的 gmail 登录,所以我以访客身份发帖)

    所以你的代码应该做一些如下的改动:

    ;(function (filename, contentType) {
    
        fs.readFile(filename, function(err, file) {
            // do the left stuff here
        });
    
    }(filename, contentType)); 
    

    【讨论】:

      【解决方案3】:

      我认为问题在于您在设置标题时在Content-Type 之后使用了不必要的:。你应该这样做 response.setHeader('Content-Type',contentType); 或者,我认为更好,这样做:response.writeHead(200,{'Content-Type':contentType});

      【讨论】:

      • 哇! 非常感谢!这就是问题所在。
      猜你喜欢
      • 1970-01-01
      • 2019-12-05
      • 2012-04-28
      • 1970-01-01
      • 2020-12-16
      • 2018-05-26
      • 2017-12-24
      • 2014-03-07
      • 1970-01-01
      相关资源
      最近更新 更多