【问题标题】:Syntax error when trying to convert HTML file to JavaScript containing socket io, SyntaxError: Unexpected token <尝试将 HTML 文件转换为包含套接字 io 的 JavaScript 时出现语法错误,SyntaxError: Unexpected token <
【发布时间】:2019-03-31 03:18:40
【问题描述】:

我想将 HTML 代码转换为 JavaScript。目前,我可以将 HTML 文件中的消息发送到 python 服务器,然后将其反转并通过套接字 io 发送回 HTML。我用过这个教程:https://tutorialedge.net/python/python-socket-io-tutorial/

我现在要做的不是通过单击网页上的按钮来发送消息,而是可以从命令行运行 JavaScript 文件,所以

节点index.js

我的 index.js 如下:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
  const socket = io("http://localhost:8080");

  function sendMsg() {   
    socket.emit("message", "HELLO WORLD");
  }

  socket.on("message", function(data) {
     console.log(data);
  });
</script>

当运行 index.js 我收到这个错误:

/home/name/Desktop/Research/server_practice/name/tutorialedge/js_communicate/index_1.js:1
(function (exports, require, module, __filename, __dirname) { <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>


SyntaxError: Unexpected token <
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:188:16)
    at bootstrap_node.js:609:3

在错误输出中,插入符号指向引号的第二部分:

socket.io/2.2.0/socket.io.js">
                            ^

我很确定这是与使用套接字 io 相结合的语法问题,但我不确定到底是什么问题。我相信我正在使用某种伪 HTML/JavaScript 代码,这就是我收到错误的原因。我是 JavaScript 新手,但我需要使用它,因为它包含我需要的 API。

为了清楚起见,这是教程中的工作 HTML 代码,index.html

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <button onClick="sendMsg()">Hit Me</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script>
      const socket = io("http://localhost:8080");

      function sendMsg() {   
        socket.emit("message", "HELLO WORLD");
      }

      socket.on("message", function(data) {
         console.log(data);
      });
    </script>
  </body>
</html>

这里是python服务器代码,server.py

from aiohttp import web
import socketio

# creates a new Async Socket IO Server
sio = socketio.AsyncServer()
# Creates a new Aiohttp Web Application
app = web.Application()
# Binds our Socket.IO server to our Web App
# instance
sio.attach(app)

# we can define aiohttp endpoints just as we normally
# would with no change
async def index(request):
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')

# If we wanted to create a new websocket endpoint,
# use this decorator, passing in the name of the
# event we wish to listen out for
@sio.on('message')
async def print_message(sid, message):
    print("Socket ID: " , sid)
    print(message)
    # await a successful emit of our reversed message
    # back to the client
    await sio.emit('message', message[::-1])

# We bind our aiohttp endpoint to our app
# router
app.router.add_get('/', index)

# We kick off our server
if __name__ == '__main__':
    web.run_app(app)

最终目标是将来自 JavaScript 的多个数据流发送到 Python 进行分析,然后发送回 JavaScript 以通过 API 输出。

【问题讨论】:

  • 你让我们猜测错误发生在哪里。编辑问题以包含完整的错误回溯消息。
  • @JohnGordon,我包含了完整的错误输出

标签: javascript python html socket.io


【解决方案1】:

脚本标签在节点中不起作用。您需要使用 require 来导入模块。

您可以使用socket.io client 模块通过node.js 连接到socket io。请注意,您必须在使用前npm install

改编自socket.io客户端自述文件的示例连接代码:

var socket = require('socket.io-client')('http://localhost:8080');
socket.on('connect', function(){});

function sendMsg() {   
    socket.emit("message", "HELLO WORLD");
}

socket.on("message", function(data) {
    console.log(data);
});

socket.on('disconnect', function(){});

【讨论】:

  • 我为客户端运行了你的建议,但是当我运行它时没有任何反应,没有错误,但是“HELLO WORLD”消息没有从 JS 脚本发送到 Python 服务器.我想我需要对 server.py 进行更改,特别是围绕以下行,“with open('index.html') as f:”
  • 我的答案中的代码是为了运行服务器端。您可以使用node index.js 运行它
  • 要清楚一点,因为我正在使用节点(节点 index.js)运行 JavaScript,这是否意味着我正在从服务器运行 JavaScript?所以我现在基本上是在 python 服务器和 JS 服务器之间进行通信?我只是想确保我完全理解我在做什么。
  • 通常使用节点使其成为服务器,除非您使用电子,它仍然是客户端。
【解决方案2】:

&lt;script&gt; 标记是 HTML 标记 - 您不能将它们放在 JavaScript 文件中。只需放置您的 JavaScript:

const socket = io("http://localhost:8080");

function sendMsg() {   
    socket.emit("message", "HELLO WORLD");
}

socket.on("message", function(data) {
    console.log(data);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    相关资源
    最近更新 更多