简体   繁体   English

如何从Socket.io事件中调用RESTful Api服务?

[英]How to call a RESTful Api Service from a Socket.io event?

I want to save a message into the database after a message is received by Socket.io server. 我想在Socket.io服务器收到消息后将消息保存到数据库中。 Here is how my event looks like on Socket.i o server side: 这是我的事件在Socket.i o服务器端的样子:

socket.on('send_msg_to_user', function (data) {
    console.log('-------------send_msg_to_user------------------');
    if(data.type == "provider"){
        io.sockets.in("user_" + data.user_id + "_" + data.provider_id).emit('new_msg', {msg: data.message});
    }else if(data.type == "user"){
        io.sockets.in("provider_" + data.user_id + "_" + data.provider_id).emit('new_msg', {msg: data.message});
    }
    console.log('-------------save_message_to_database------------------');
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://165.227.33.135/message/save?user_id=218&provider_id=206&message=hrthtrhtr&type=up&request_id=899", false);
    xhr.send();
});

The first part is working well. 第一部分运行良好。 The problem is when I try to create a XMLHttpRequest object, I can't. 问题是当我尝试创建XMLHttpRequest对象时,我做不到。 Here is the error I keep receiving. 这是我一直收到的错误。

ReferenceError: XMLHttpRequest is not defined ReferenceError:未定义XMLHttpRequest

I also tried another way to call my webservice, without XMLHttpRequest: 我还尝试了另一种无需XMLHttpRequest即可调用我的Web服务的方法:

socket.on('send_msg_to_user', function (data) {
    console.log('-------------send_msg_to_user------------------');
    if(data.type == "provider"){
        io.sockets.in("user_" + data.user_id + "_" + data.provider_id).emit('new_msg', {msg: data.message});
    }else if(data.type == "user"){
        io.sockets.in("provider_" + data.user_id + "_" + data.provider_id).emit('new_msg', {msg: data.message});
    }
    console.log('-------------save_message_to_database------------------');
    url = 'http://165.227.33.135//message/save?user_id=' + data.user_id
        + '&provider_id=' + data.provider_id
        + '&message=' + data.message
        + '&type=' + data.type
        + '&request_id=' + socket.reqid;
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    });
});

In this case it seems that the webservice is not triggered as expected and the web api is returning a basic 404 error. 在这种情况下,似乎未按预期触发Web服务,并且Web api返回了基本的404错误。

XMLHttpRequest is not a default package in node (I guess your server is using node.js). XMLHttpRequest不是节点中的默认软件包(我想您的服务器正在使用node.js)。 You can use any node package for requests like request https://github.com/request/request 您可以将任何节点包用于请求https://github.com/request/request之类的request

There is also a separate xmlhttprequest package for node: https://www.npmjs.com/package/xmlhttprequest 节点还有一个单独的xmlhttprequest包: https : xmlhttprequest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM