Node.js 错误资源被解释为样式表,但在nojd.js简单应用程序中使用MIME类型text/html:传输
在node.js中创建简单html、css应用程序时遇到以下错误: 错误资源被解释为样式表,但使用MIME类型text/html传输: server.js代码是:Node.js 错误资源被解释为样式表,但在nojd.js简单应用程序中使用MIME类型text/html:传输,node.js,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 reque
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">
您可以使用
路径
模块识别扩展名,并相应地设置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());
您可以使用
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());