首页 > 解决方案 > 如何在不重新加载 socket.io 的情况下在聊天框上进行聊天显示

问题描述

我似乎无法弄清楚这个问题。我有一个在 wpengine 上运行的应用程序,它使用 WordPress 和 vue.js 和 socket.io 来提供聊天功能。主要问题是每次我在聊天框中发布内容时,它都不会显示任何内容,直到我重新加载页面。我不确定我做错了什么。

这是来自控制台的错误

注意:我有两个聊天框在一个页面上运行。

这是我的 server.js 代码

#!/usr/bin/env node
const fs = require('fs');

let http = require('http').Server((req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({"status": "ok"}));
});
let https = require('https').Server(getOptions());

let io_http = require('socket.io')(http);
let io_https = require('socket.io')(https);

let Redis = require('ioredis');

let redis = new Redis();
redis.psubscribe("*");

redis.on('pmessage', function (p, c, m) {
    io_http.emit(c, m);
    io_https.emit(c, m);
});

io_http.sockets.on("connection", function (socket) {
    socket.emit("foo", "Now, we are connected");
});
io_https.sockets.on("connection", function (socket) {
    socket.emit("foo", "Now, we are connected");
});

https.listen(2042, function () {
    console.log('Server https start');
});

http.listen(2041, function () {
    console.log('Server http start');
});


function getOptions() {
const keyPath = '"ssl certs"';
const certPath = '"ssl certs"';

let lastTime = 0;
let certFile = "";
let keyFile = "";


}

这是 chat.js 部分

class Chat {

    constructor(parametrs) {
        this.id = parametrs.id;
        this.user_id = parametrs.user_id || 0;
        this.nonce = parametrs.nonce;
        this.data_form_id = 'data-form-id-' + parametrs.id;
        this.data_chat_id = 'data-chat-id-' + parametrs.id;

        this.send_action = 'add_message';
        this.get_action = 'get_message';
        this.url = parametrs.action;
        this.time = new Date().getTime();
        this.template = parametrs.template;
        this.likes = [];
        this.dislikes = [];
        this.inProgressLike = false;
        this.isAjax = parametrs.isAjax || 'Y';

        this.bind();
        this.scrollChat();
        //alert(this.addMessage());
        let port = location.protocol === 'https:' ? '2089' : '2041';

        let socket = io(location.protocol + '//' + location.hostname + ':' + port);
        socket.on(this.id, (d) => {
            try {
                d = JSON.parse(d);
            } catch (e) {
                d = {}
            }
            if (d.status == "success") {
                if (d.content) {
                    alert(d.content);
                    console.log(typeof d.content)
                    this.addMessage(d.content);

                }
                if (d.likes) {
                    this.addLikes(d.likes);
                }
            }
        });
        socket.on('error', function (data) {
             alert(JSON.stringify(data));
            console.log(data || 'error');
        });
    }

    bind() {
        let self = this;
        $('[' + this.data_form_id + ']').on('submit', function (e) {
            e.preventDefault();
            self.sendMessage(this);
            alert(this.data_chat_id);
        });

        let likes = document.querySelector('[data-chat-id-' + this.id + ']').querySelectorAll('.likes__item');
        if (likes !== null) {
            likes.forEach(function (l) {
                l.addEventListener('click', function (e) {
                    self.sendLike(this)
                })
            });
        }
    }

    unbind() {
        let likes = document.querySelector('[data-chat-id-' + this.id + ']').querySelectorAll('.likes__item');
        if (likes !== null) {
            likes.forEach(function (l) {
                var old_element = l;
                var new_element = old_element.cloneNode(true);
                old_element.parentNode.replaceChild(new_element, old_element);
            });
        }
    }

    sendMessage(target) {

        let self = this;
        let text = target.querySelector('input[name="text"]').value;
        target.querySelector('input[name="text"]').value = '';

        if (text.length <= 0) {
            return false;
        }

        let data = {
            text: text,
            chat_id: this.id,
            action: this.send_action,
            time: new Date().getTime(),
            user_id: this.user_id,
            template: this.template,
            nonce: this.nonce
        };

        $.ajax({
            url: target.action,
            data: data,
            method: 'POST',
            success: function (r) {
                if (self.isAjax == 'N') {
                   // self.getMessage()

                }
            },
            error: this.onError
        });
       
    }

    sendLike(target) {

        if (this.inProgressLike) {
            return false;
        }

        this.inProgressLike = true;

        let self = this;
        let type = target.getAttribute('data-type-like');
        let messid = target.parentNode.getAttribute('data-message-id');
        let s = target.querySelector('span');

        $.ajax({
            url: this.url,
            method: 'POST',
            data: {
                type: type,
                action: 'send_like',
                mess_id: messid,
                user_id: this.user_id,
                time: new Date().getTime(),
                chat_id: this.id
            },
            success: function (d) {
                d = JSON.parse(d);
                self.inProgressLike = false;
                if (self.isAjax == 'N') {
                    //self.getMessage();
                }
            }
        });


    }

    addMessage(c) {
        //alert(c);
        let parent = $('[' + this.data_chat_id + '] .people-chat__item').parent()[0];
        $(parent).prepend(c);
        this.scrollChat();
    }

    getMessage() {

        let self = this;
        let data = {
            action: this.get_action,
            chat_id: this.id,
            user_id: this.user_id,
            time: this.time,
            template: this.template
        };
        this.scrollChat();
        $.ajax({
            url: this.url,
            data: data,
            method: 'POST',
            success: function (r) {

                self.time = new Date().getTime();
                let d = JSON.parse(r);
                if (d.status == "success") {
                    if (d.content) {
                        self.addMessage(d.content);
                    }
                    if (d.likes) {
                        self.addLikes(d.likes);
                    }
                }

            },
        }).always(
            function () {
                if (self.isAjax == 'Y') {
                    //self.getMessage();
                }
                self.unbind();
                self.bind();
            }
        );
    }

    addLikes(likes) {
        for (let m_like in likes) {


            let mess = document.querySelector('[data-message-id="' + likes[m_like].message_id + '"]');
            let like = mess.querySelector('[data-type-like="likes"]>span');
            let dislike = mess.querySelector('[data-type-like="dislikes"]>span');

            like.innerHTML = likes[m_like].likes || 0;
            dislike.innerHTML = likes[m_like].dislikes || 0;
        }
    }


    scrollChat() {
        
    }
}

标签: javascriptphpwordpressvue.jssocket.io

解决方案


我不确定你想做什么,但如果你想阻止你的页面重新加载,那么你必须使用

form.addEventListener('submit', (e)=>{
e.preventDefault()})

这里的表单是发送消息的输入-提交表单。


推荐阅读