简体   繁体   中英

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. Here is how my event looks like on Socket.i o server side:

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. Here is the error I keep receiving.

ReferenceError: XMLHttpRequest is not defined

I also tried another way to call my webservice, without XMLHttpRequest:

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.

XMLHttpRequest is not a default package in node (I guess your server is using node.js). You can use any node package for requests like request https://github.com/request/request

There is also a separate xmlhttprequest package for node: https://www.npmjs.com/package/xmlhttprequest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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