简体   繁体   English

使用Node.js和Socket.IO服务静态文件

[英]Serve static files with Node.js & Socket.IO

Although I already browsed some answers both here on SO and the net, I didn't find what I was looking for. 尽管我已经在SO和网络上浏览了一些答案,但没有找到所需的内容。 I am also a newb in Node.js so perhaps that's the problem. 我也是Node.js的新手,所以也许就是问题所在。

This is the code that I have and need for starting Node and Socket.IO: 这是启动Node和Socket.IO所需的代码:

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

What I need next would be something like this: 接下来,我需要的是这样的东西:

http.use(app.static(__dirname + "/public"));

"app has no method 'static' " is my problem. “应用程序没有方法'静态'”是我的问题。 I tried several other combinations to get both what I read on the net regarding including static css and js and serving httpServer instance to Socket.IO. 我尝试了几种其他组合,以使我同时在网上阅读有关静态CSS和JS以及将HttpServer实例提供给Socket.IO的内容。

Thanks :) 谢谢 :)

Try this: 尝试这个:

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

express.static is the method you're looking for, not app.static , though they would seem identical. express.static是您要查找的方法,而不是app.static ,尽管它们看起来相同。

Also, see this for an example of an application using both socket.io and express. 另外,请参阅示例以了解同时使用socket.io和express的应用程序示例。 Note that they only use the http server for socket.io , not serving the web pages. 请注意,他们仅将http服务器用于socket.io ,而不为网页提供服务。

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

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