gpt4 book ai didi

javascript - django 模板中的socket.io - node.js 不服务socket.io.js

转载 作者:行者123 更新时间:2023-12-02 17:51:30 26 4
gpt4 key购买 nike

我有 Django 应用程序,需要使用实时推送到客户端。
我想使用node.js和socket.io(我知道这是今天最简单的平台..)。
为了实现它,我将 socket.io 框架代码放在模板上:

{% extends "base.html" %}

{% block content %}
{% if error %}
<div id="error">
<h3>{{ error }}</h3>
</div>
{% endif %}
<div id="reply">

<script src="http://localhost:8889/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>

var socket = io.connect('http://localhost:8889');

socket.on('connect', function(){
socket.emit('addOrder', 99, {{ reply_id }});
});

</script>
Thank you for your reply
</div>
{% endblock %}
正如你所看到的,我的node.js在8889上运行..所以我需要调用“script src”从localhost:8889/socket.io/socket.io.js(Django服务器和node.js)导入它。 js 服务器是同一台服务器。这就是我使用 localhost 的原因)。

问题是,当我调用此模板(从 View 中渲染它)并在 chrome 上使用 F12 时,我看到“警告:显示临时标题。”。
我试图在这里检查这是什么意思,但我只看到有关 AdBlocks 的讨论,所以我卸载了它,但我仍然收到此错误...

经过更多调查后,我发现即使在 apache( native HTML 文件)上我也无法获取 js 文件(相同的错误)。

看起来原因是我必须使用node.js http服务器(express)来提供该文件,并且无法从任何其他Web服务器调用它。

有谁知道可能是什么原因或如何解决它?

Node.js 服务器代码:

var express = require("express");
var app = express();
var io = require('socket.io').listen(app.listen(8889));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/menu.css', function (req, res) {
res.sendfile(__dirname + '/menu.css');
});
var branches = {};
ojson = {"count":1,"orders":[{"id":100,"state":"ok"}]};
io.sockets.on('connection', function (socket) {
socket.on('connectBranch', function(branchID) {
//save ID info on the socket
socket.branchID = branchID
// save the socket of the branch by ID
branches[branchID]=socket;
// ask the client to run getAll function with orders JSON
branches[branchID].emit('getAll', ojson);
});

// clear - for test
socket.on('clearOrders', function(branchID) {
branches[branchID].emit('clearOrders');
});

// when the client emits 'addOrder', this listens and executes
socket.on('addOrder', function(branchID, orderID){
console.log(branches);
branches[branchID].emit('addOrder', orderID);
});

// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the branch from global branches list
delete branches[socket.branchID];
});
});

最佳答案

除非您在本地主机上运行它

<script src="http://localhost:8889/socket.io/socket.io.js"></script>

需要改为

<script src="http://SERVER_IP:8889/socket.io/socket.io.js"></script>

更好的是,如果您的前端 HTTP 服务器是 NGINX 或类似服务器,您可以将对 socket.io.js 的调用代理到端口 8889,然后将您的页面更改为

<script src="/socket.io/socket.io.js"></script>

这样你就不必指定IP,它将与原始HTML页面的来源相同

关于javascript - django 模板中的socket.io - node.js 不服务socket.io.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21309534/

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