【发布时间】: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