使用 Node.js、Socket.IO 和 Express 提供静态 JavaScript 文件 [英] Serving static javascript files with Node.js, Socket.IO and Express

查看:21
本文介绍了使用 Node.js、Socket.IO 和 Express 提供静态 JavaScript 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 node.js 应用程序,它使用 socket.io 和 express.目前所有的 javascript 都在 HTML 文件中,但我想尝试将它分离成一个 .js 文件.

I have a simple node.js application which uses socket.io and express. At the moment all of the javascript is in the HTML file but I would like to try and separate it out into a .js file.

在我的主节点应用程序中,我有这个:

In my main node application I have this:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

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

这工作正常,直到我将我的 javascript 从 index.html 移动到 .js 文件然后尝试从我的 HTML 文件中引用它,如下所示:

This works fine until I move my javascript from index.html to a .js file then try to reference it from my HTML file like this:

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

我认为 express 不提供静态文件,所以我试过了:

I think that express is not serving the static file so I have tried this:

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/functions.js');
});

谁能告诉我我做错了什么?

Can anyone tell me what I am doing wrong?

推荐答案

nodejs 和 express 默认不提供任何文件.因此,当您创建第一条路线时:

nodejs and express do not serve ANY files by default. So, when you created your first route:

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

这成功地允许浏览器请求 / 查看您的 index.html 文件.然后浏览器将接收该 HTML 文件并对其进行解析.如果它在该文件中找到

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆