繁体   English   中英

Node.js-样式不适用于页面,Google Chrome表示:Uncaught SyntaxError:意外令牌

[英]Node.js - Styles doesn't apply to page & Google Chrome says: Uncaught SyntaxError: Unexpected token <

我开始研究node.js,并一开始就陷入困境。 我试图几次解决这个问题,但没有成功。 我在谷歌上搜索,堆栈溢出并发现了类似我的问题。 但是不完全正确,或者解决方案对我不起作用。 请帮我!

我有以下内容的简单index.html文件:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>SimpleApp</title>
  <link rel="stylesheet" type="text/css" href="styles/default.css" />
</head>
<body>

  Hello, Node!
  <script src="js/application.js"></script>

</body>
</html>  

这是server.js文件中的简单服务器:

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

var server = http.createServer(function(request, response) {
  fs.readFile('./index.html', function(error, data) {
    if(error) {
      response.writeHead(404, {'Content-Type' : 'text/html'});
      response.end('<h1>File <index.html> not found.</h1>');
    } else {
      var contentType = undefined;
      if(request.url === '/') {
        contentType = 'text/html';
      } else {
        contentType = mime.lookup(request.url);
      }
      response.writeHead(200, {'Content-Type' : contentType});
      response.end(data);
    }
  });
});

server.listen(8000, function() {
  console.log('Server started.');
})

启动服务器后,样式不适用于页面,Google Chrome会显示: Uncaught SyntaxError:意外令牌<
我知道fs.readFile回调内部的问题,在其他地方 ,但是什么?

这是一个解决方案(需要重构):

server.js

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

var server = http.createServer(function(request, response) {
  var filePath = undefined;
  var contentType = undefined;

  switch(request.url) {
    case '/':
      filePath = './index.html';
      contentType = 'text/html';
      break;
    case '/styles/default.css':
      filePath = './styles/default.css';
      contentType = mime.lookup(request.url);
      break;
    case '/js/application.js':
      filePath = './js/application.js';
      contentType = mime.lookup(request.url);
      break;
    default:
      filePath = request.url;
      contentType = mime.lookup(request.url);
  }

  fs.readFile(filePath, function(error, data) {
    response.writeHead(200, {'Content-Type' : contentType});
    response.end(data);
  });
});

server.listen(8000, function() {
  console.log('Server started.');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM