1

我正在使用 Octoprint Javascript API ( http://docs.octoprint.org/en/master/jsclientlib/index.html ) 制作仪表板,以便一次查看多台打印机以用于学校项目。这将在与我的 OctoPi 完全分开的 Web 服务器上运行。我一直在使用 REST API 来获取数据,但始终无法让套接字正常工作。我发现了 Javascript API 并已将其用于基本请求,但希望与套接字连接以获取有关打印机状态的更新数据。很简单,我在我的 HTML 中添加了以下几行并进行了一些测试:

<script src="sockjs.min.js"></script> (Downloaded a copy of sockjs from their github page yesterday)
<script src="packed-client.js"></script> (Downloaded this by opening octopi.local and copying the source)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<body>
        <div id="test_area"></div>

        <script>
                OctoPrint.options.baseurl = (my ip here);
                OctoPrint.options.apikey = (api key here);

                OctoPrint.socket.connect();

                OctoPrint.socket.onMessage("*", function(message){
                       document.getElementById('test_area').innerHTML = response;
                });
        </script>
</body>

onMessage 处理程序甚至永远不会触发。我在 Chrome 中收到此错误:

XMLHttpRequest 无法加载http://(my ip here)/sockjs/info?t=1490302299698。当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。因此,Origin 'null' 不允许访问。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

CORS 和 SockJS 似乎存在问题。

这些是标题:

Request URL:http://(my ip here)/sockjs/info?t=1490302365251
Request Method:GET
Status Code:200 OK
Remote Address:(ip here):80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:*
Cache-Control:no-store, no-cache, must-revalidate, max-age=0
Content-Length:77
Content-Type:application/json; charset=UTF-8
Date:Thu, 23 Mar 2017 20:52:45 GMT
Etag:"d88498e8b1e0e1a411f64eb3eb6e219315b36ef4"
Server:TornadoServer/4.0.2
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:session_P80=eyJfaWQiOnsiIGIiOiJNVGRrWm1OalpEZzRZV00xTkRNd1lqZzJOMkpsWkRCbU4yWTFaR1JpTmpZPSJ9fQ.C7W5Xg.DmKIY6AJktPrR8_8Es8wa9iBc10
Host:(ip here)
Origin:null
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36

任何想法如何让这个工作?这是我能做的最基本的设置,但它不起作用。谢谢!

4

1 回答 1

1

Alright, the issue ended out being that I was running the website directly in the browser (via file:// instead of through a web server), plus small errors that were copied over from my larger example code (response vs message variable names, plus I forgot to copy over the JQuery import that was in my other code). There was also a bug in Octoprint that made subscribing to "*" not work, but according to the developer, there will be a fix in the next version. So, in short, spin up a web server, get the new software when it is released (1.3.3).

于 2017-03-27T16:53:37.590 回答