gpt4 book ai didi

javascript - 意外 token : io. 监听(服务器)

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:56 27 4
gpt4 key购买 nike

我是 node.js 的新手。按照一些教程,我创建了一个名为 server.js 的文件,并将以下代码放入该文件中:

var http = require("http");
var url = require('url');
var fs = require('fs');

var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
console.log(path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket.html':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('Inside hello world');
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 403");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write(data, "utf8");
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 405");
break;
}
response.end();
});

server.listen(8001);

var io.listen(server);

然后我使用以下命令运行此命令:node C:\Users\user\Desktop\server.js 并收到此错误:

C:\Users\user\Desktop\server.js:38
var io.listen(server);
^
SyntaxError: Unexpected token .
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3

此行导致错误:

var io.listen(server);

最初我想安装 npmsocket.io 因此我尝试了这个:

npm install --save socket.io

但在此之后我也遇到了同样的错误:

C:\Users\user\Desktop\server.js:38
var io.listen(server);
^
SyntaxError: Unexpected token .
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3

请告知如何解决此错误。

最佳答案

var 关键字用于声明变量。我怀疑您缺少变量名称:

var foo = io.listen(server);

除此之外,代码中的其他任何地方都没有 io 。您是否错过了 require 调用?

<小时/>

socket.io 库显然没有捆绑:

C:\>node
> require("socket.io");
Error: Cannot find module 'socket.io'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at repl:1:1
at REPLServer.self.eval (repl.js:110:21)
at repl.js:249:20
at REPLServer.self.eval (repl.js:122:7)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)

Installation虽然是单行:

npm install socket.io

关于javascript - 意外 token : io. 监听(服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26022160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com