简体   繁体   English

如何使用express和nodeJS将javascript文件链接到html页面

[英]How to link a javascript file to an html page using express and nodeJS

My nodeJS app is very simple, but I am having difficulty linking my javascript file to it. 我的nodeJS应用程序非常简单,但我很难将我的javascript文件链接到它。 Normally, you would just put the script in the header. 通常,您只需将脚本放在标题中即可。 That doesn't work with Node, apparently, so have tried to link it through sendFile and some other methods, but none have worked. 显然,这不适用于Node,所以试图通过sendFile和其他方法链接它,但没有一个有效。

My Javascript is simply: 我的Javascript很简单:

var express = require('express');
var app = express();


app.get('/',function(req, res) {
    res.sendFile(__dirname + '/index.html');
    res.send()
});
app.listen(8888)

My HTML is also simple: 我的HTML也很简单:

<html>
<head>
    <title>Charter</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
    <div id="container" style="width:100%; height:400px;"></div>
    <button id="button" class="autocompare" onclick="plotNewChart()">Add series</button>
    <script type="text/javascript">
         $(function () { $('#container').highcharts({ chart: { events: { addSeries: function () { var label = this.renderer.label('A series was added, about to redraw chart', 100, 120).attr({ fill: Highcharts.getOptions().colors[0], padding: 10, r: 5, zIndex: 8 }) .css({ color: '#FFFFFF' }) .add(); setTimeout(function () { label.fadeOut(); }, 1000); } } }, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }); });
    </script>
</body>
</html>

What I want to do is link another file, myJS.js . 我想要做的是链接另一个文件myJS.js I don't know how to do that without the typical ` 没有典型的`我不知道怎么做

You need to setup your Express server to serve static files. 您需要设置Express服务器以提供静态文件。 At the moment, it appears to only serve the '/' route. 目前,它似乎只服务于'/'路线。

Just before you setup your routing, add the line below. 在设置路由之前,请添加以下行。 You can then serve up static assets from a 'public' folder relative to where your script it. 然后,您可以从“公共”文件夹中提供相对于脚本位置的静态资源。

app.use(express.static(path.join(__dirname, 'public')));

So if you put your myJS.js in public/js/myJS.js you can then reference it like so 所以,如果你把你的myJS.js放在public/js/myJS.js你可以像这样引用它

<script src="/js/myJS.js"></script>

More info in the docs: http://expressjs.com/api.html#express.static 更多信息请参阅文档: http//expressjs.com/api.html#express.static

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

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