【发布时间】:2017-03-17 06:56:48
【问题描述】:
我在控制台 GET http://localhost/socket.io/socket.io.js 404(未找到)中收到此错误。我使用 npm install 来安装 express 和 socket.io。
每次我尝试访问 localhost:3000 时,它都会下载一个文件而不是显示 chat.php
这是我的 JavaScript 代码
var express = require('express')
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(3000);
users = [];
connnection = [];
console.log('Server running!');
app.get('/',function(req, res){
res.sendFile(__dirname + '/game.php');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//Disconnect
socket.on('disconnect', function(data){
connections.splice(connections.indexOf(socket),1);
console.log('Disconnected: %s sockets connected', connections.length);
});
});
这就是我添加到 php 文件中的内容
<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
var socket=io.connect();
});
</script>
【问题讨论】:
-
您希望
res.sendFile(__dirname + '/game.php')发生什么?您是否了解 PHP 不在用户的浏览器中运行,而仅在服务器上运行,因此将 PHP 文件发送到浏览器(这就是您正在做的事情)不会做一些有用的事情?当你做res.sendFile(__dirname + '/game.php');时你想发生什么? -
@jfriend00 我是这个 socket.io 的新手,我正在学习教程。在该教程中,当访问 localhost:3000 时,它被重定向到 chat.html
-
我想我明白了...当您通常访问(例如)www.example.com/page.php 时,您会看到该网页,并且它的工作方式与您之前的相同去了 www.example.com/page.html 但 php url 实际上返回了 php 文件的 HTML 解释。在这个例子中,我不相信这会起作用,因为 node.js 不知道首先通过解释器运行你的
game.php。如果您将其重命名为game.html,它应该可以按预期工作,因为您的文件中没有 php 代码。 -
game.php 中有什么?它是 PHP 文件还是 HTML 文件?你能在你的问题中显示它的内容吗?
-
@jfriend00 这是一个php文件
标签: javascript node.js sockets