【问题标题】:Weird mime-type overwrite issue when serving static files from NodeJS从 NodeJS 提供静态文件时出现奇怪的 mime 类型覆盖问题
【发布时间】:2018-03-22 09:10:05
【问题描述】:

我正在使用 NodeJS 从我的视图目录中提供文件(没有快递)。我正在关注一个应用程序、服务器、路由器、处理程序结构,其中处理程序拥有几乎所有代码。

这里是 handler.js 的代码:

const fs = require('fs'),
path = require('path'),
formidable = require('formidable');

function handle(pathname, method, viewDir, response){
    let filePath;
    console.log(pathname);
    if(pathname==='/'){
        pathname = '/main.html';
    }

    if(pathname==='/favicon.ico'){
        debugger;
        response.end();
    }
    else{
        filePath = viewDir + pathname;
        //fileext = pathname.substr(pathname.lastIndexOf('.')+1);   
        fileExt = path.extname(pathname);
        console.log(filePath+'\n'+fileExt);
        if(fileExt!==''){
            fs.readFile(filePath, function(err,data){
                if(err){
                    response.writeHead(400, {'Content-Type': 'text/html'});
                    response.end('<h1>Error reading file!</h1>');
                }
                if(data){
                    debugger;
                    // console.log({'Content-Type': 'text/' + fileExt.substr(1)=='js'?'javascript':fileExt.substr(1)});
                    let mimeType = 'text/' + (fileExt.substr(1)=='js'?'javascript':fileExt.substr(1));
                    console.log(mimeType);
                    response.writeHead(200, {'Content-Type': mimeType});
                    response.write(data);
                    response.end();
                }
            });
        }   
        else if(pathname==='/upload' && method.toLowerCase()==='post'){
            //some formidable code here
            response.end();
        }
        else{
            response.writeHead(404, {'Content-Type': 'text/html'});
            response.end('<h1>404 File not found!</h1>');
        }
    }

}

    exports.handle = handle;

这是 main.html:

    <!DOCTYPE html>
<html>
<head>
    <title>Caption generator for images</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="./main.css"></link>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
    <div class="jumbotron">
        <h1>Caption generator for images</h1>
        <h3>Generates a list of captions appropriate for your uploaded picture by visual recognition.</h3>
    </div>
    <div class="container">
        <div class="page-header">
            <h1>Upload image</h1>
        </div>
        <form enctype="multipart/form-data">
            <div class="form-group">
                <label for="imageInputFile">Image input</label>
                <input id="image-input-file" type="file" class="form-control-file" name="image-input-file" aria-describedby="fileHelp" accept="image/*">
                <small id="fileHelp" class="form-text text-muted">Upload an image file or use already uploaded image.</small>
            </div>
            <button type="submit" id="file_submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
    <script type="text/javascript" src="main.js"></script>
</body>
</html>

现在,如果我从 main.html 中删除最后一个脚本标记,一切都会正常加载,但如果它存在,我的 main.css 文件将使用 mime 类型的文本/javascript 提供服务。

我没看到什么?

我还看到两个文本/javascript 被记录,它们都在 main.js 被提供之后。如果我在我的脚本标签之后剪切并粘贴我的 main.css 的链接标签,它们都将作为文本/css 提供。

这与我的 fileExt 是一个全局变量有关吗?

【问题讨论】:

    标签: javascript html css node.js mime-types


    【解决方案1】:

    我认为您在 ServerSide 和 ClientSide 之间的路径之间存在混淆。 在您的 HTML 中,css 与 ./main.css 一起使用,但对于 JS,您直接使用 main.js

    我没有完整的项目来检查正在加载的文件夹/URL。

    有理由不使用 ExpressJS 吗? 例如,如果您的目录如下:

    app/
    app/index.js
    app/public/{here your css, main}
    

    在 index.js 中 你只需要

    const express = require('express');
    const app = express();
    
    app.use('/', express.static('public'));
    
    app.listen(3000, function () {
      console.log('Example app listening on port 3000!')
    });

    【讨论】:

    • 我这里尽可能多地去香草只是为了学习。至于网址,它们看起来还不错,我可以在 chrome 下的源选项卡中看到文件。所有静态文件都存在于一个名为 views 的目录中。
    【解决方案2】:

    我未能声明变量 fileExt。我的错!

    let fileExt;
    

    在声明路径名变量之后或首次使用“fileExt”之前的任何位置插入上述语句可以解决问题。

    【讨论】:

      猜你喜欢
      • 2012-09-04
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      相关资源
      最近更新 更多