如何使用 express 和 nodeJS 将 javascript 文件链接到 html 页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26108623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to link a javascript file to an html page using express and nodeJS
提问by maudulus
My nodeJS app is very simple, but I am having difficulty linking my javascript file to it. 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.
我的 nodeJS 应用程序非常简单,但是我很难将我的 javascript 文件链接到它。通常,您只需将脚本放在标题中即可。显然,这不适用于 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. I don't know how to do that without the typical `
我想要做的是链接另一个文件,myJS.js. 如果没有典型的`
回答by moonthug
You need to setup your Express server to serve static files. At the moment, it appears to only serve the '/' route.
您需要设置 Express 服务器来提供静态文件。目前,它似乎只服务于“/”路线。
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.jsin public/js/myJS.jsyou 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

