node.js - 错误资源解释为样式表但使用 MIME 类型 text/html : in nojd. js simple app 进行传输

标签 node.js

在node.js中创建简单的html、css应用程序时遇到以下错误: 错误资源解释为样式表但使用 MIME 类型 text/html 传输:

server.js 代码是:

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

// Create a server
http.createServer( function (request, response) {  
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;

// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");

// Read the requested file content from file system
fs.readFile(pathname.substr(1), function (err, data) {
  if (err) {
     console.log(err);

     // HTTP Status: 404 : NOT FOUND
     // Content Type: text/plain
     response.writeHead(404, {'Content-Type': 'text/html'});
  } else {  
     //Page found     
     // HTTP Status: 200 : OK
     // Content Type: text/plain
     response.writeHead(200, {'Content-Type': 'text/html'});    

     // Write the content of the file to response body
     response.write(data.toString());       
  }

  // Send the response body 
  response.end();
 });   
}).listen(9999);

// Console will print the message
console.log('Server running at http://127.0.0.1:9999/');

index.html

<link rel="stylesheet" type="text/css" href="css/style.css">

最佳答案

您可以使用 path 模块来识别扩展名并相应地设置 mime 类型:

// require path module
var path = require('path');

// check for extenstion
var pathname = url.parse(request.url).pathname;
var ext = path.extname(pathname).substr(1);

// check extension and set mime type
// HTTP Status: 200 : OK
if (ext === 'css') {
  // check for css
  response.writeHead(200, {'Content-Type': 'text/css'});
} else {
  // Content Type: text/plain
  // maybe also check .html type
  response.writeHead(200, {'Content-Type': 'text/html'});
}

// Write the content of the file to response body
response.write(data.toString());

关于node.js - 错误资源解释为样式表但使用 MIME 类型 text/html : in nojd. js simple app 进行传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55923726/

相关文章:

node.js - 如何在mongoDB中分组并返回结果中的所有字段

node.js - Axios - 如何修复 - POST URL net::ERR_CONNECTION_RESET

node.js - 为什么我无法安装特定版本的 npm 以及如何安装?

javascript - 获取与请求

javascript - Node.js - 将数据发送到 Node.js 并以 HTML 形式验证插入的数据

javascript - 使用 gulp 索引 Nodejs 或 browserify 组件

javascript - Google API - 未找到文件 ID - 但返回的数据对应于我输入的folderId

node.js - bubblewrap init 抛出 -bash : bubblewrap: command not found

javascript - 覆盖 require 从 root 启动并检查 Node 模块而不更改其名称

node.js - 在Mac上运行 'bower install'