用nodejs和express读取css / js文件

时间:2016-02-20 12:42:57

标签: javascript html node.js

对于nodejs,我是一个真正的菜鸟,jsut几天前开始这样做。我无法弄清楚为什么我的js和css文件没有被应用。没有404错误,所以似乎不是这样。我正在尝试使用express来读取文件。我在开发工具中遇到这些控制台错误:

GamblerScript.js:1 Uncaught SyntaxError:意外的令牌<

jquery-2.2.0.min.js:1未捕获的SyntaxError:意外的令牌<

localhost /:5资源被解释为样式表,但使用MIME类型text / html进行传输:“http://localhost:8080/css/Stylesheet.css”。

(index):9未捕获的ReferenceError:未定义运行

是否有人能够看到我做错了什么?

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
var express = require('express');
var app = express();

app.get('/', function(req, res) {
  res.sendfile('/index.html');
});
app.use(express.static(__dirname + '/public'));

fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8080);
});
<html lang="en">
<head>
    <title>Dices</title>
    <link rel="stylesheet" href="/css/Stylesheet.css">
    <script src="/js/GamblerScript.js"></script>
    <script src="/js/jquery-2.2.0.min.js"></script>
</head>
<body onload="Run();">
<div id="spinboxcontainer">
    <div class="spinbox">
        <span class="spinspan">Dices</span>
    </div>
<div id="container">
    <div id="spinner1" class="spinner">
        <div id="D1.1" class="one">1</div>
        <div id="D1.2" class="two">2</div>
        <div id="D1.3" class="three">3</div>
        <div id="D1.4" class="four">4</div>
        <div id="D1.5" class="five">5</div>
        <div id="D1.6" class="six">6</div>
    </div>
</div>
<div id=container2>
    <div id="spinner2" class="spinner">
        <div id="D2.1" class="one">6</div>
        <div id="D2.2" class="two">5</div>
        <div id="D2.3" class="three">4</div>
        <div id="D2.4" class="four">3</div>
        <div id="D2.5" class="five">2</div>
        <div id="D2.6" class="six">1</div>
    </div>
</div>
</div>
</body>
</html>

function Run(){
    alert('Welcome');
var clickNumber = 1; 
document.getElementById('spinner1').addEventListener("click", function(){
        alert('Your click is number ' + clickNumber + '!');
        document.body.className -= ' WhiteBackground';
        clickNumber = clickNumber + 1;
});

document.getElementById('spinner2').addEventListener("click", function(){
        alert('Your click is number ' + clickNumber + '!');
        document.body.className += ' WhiteBackground';
        clickNumber = clickNumber + 1;
});
};

2 个答案:

答案 0 :(得分:2)

你弄乱了不同的方法。如果您使用express,则无需http.createServer并使用fs.readFile手动阅读静态文件。对于简单的静态服务器,只需像这样简化主文件

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080, function() {console.log('server listening on port 8080...')})

您遇到的错误是因为每当浏览器向服务器询问jqueryGamblerScript等脚本文件时,您的自定义http服务器都会将index.html文件发回,而浏览器尝试执行它就像javascript一样。

答案 1 :(得分:1)

有些事情你做错了。

在代码的下半部分,在传递给fs.readFile()的回调中,您创建了一个 Node 服务器来处理所有请求。强调的话语在这里是关键:您只使用Node的内置功能创建服务器,使用Express时您不需要这样做;并且服务器处理所有请求,而不仅仅是那些index.html文件的请求,正如我所想的那样。因此,当您的CSS和JavaScript请求进入时,您发送index.html作为回复。这不会做。

幸运的是,解决方案比原始问题简单。就这样做:

'use strict';

const path = require('path');
const express = require('express');
const app = express();

// This just lets you set an alternate port with an environment variable,
// if you want.
const PORT = process.env.PORT || 8080;

// Set your static folder before any request handlers.
app.use(express.static(path.resolve(__dirname, 'public')));

// Handles request to root only.
app.get('/', (req, res) => {

  // If you needed to modify the status code and content type, you would do so
  // using the Express API, like so. However, this isn't necessary here; Express
  // handles this automatically.
  res.status(200);
  res.type('text/html');

  // Use sendFile(absPath) rather than sendfile(path), which is deprecated.
  res.sendFile(path.resolve(__dirname, 'index.html'));
});

// Call the listen() method on your app rather than using Node's http module.
app.listen(PORT, (err) => {
  if (err) throw err;
  else console.log(`Listening on port ${PORT}`);
});