I'm using express-ws to perform socket routing. I want to create an API (mostly a POST API). On hitting the API, it should emit events through sockets.
app.ws('/echo', function(ws, req) {
ws.on('message', function(msg) {
ws.send("Hello World!");
});
ws.send("Testing something");
console.log("Hello world!");
});
The above is my code and the code below is my browser code.
$(function() {
var ws = new WebSocket("ws://localhost:3000/echo");
ws.onopen = function() {
console.log("Web Socket open!");
//ws.send("Hi!");
};
ws.onerror = function(err) {
console.log("Web socket error: " + err);
};
ws.onclose = function() {
console.log("Web socket closing: ");
};
ws.onmessage = function(data) {
console.log("Web socket receiving data: ");
console.log(data.data)
};
});
I can see that the browser is able to setup a connection. How can I externally hit this API? I cannot find any doc on whether it should be a GET request or a POST request and when I try the below code. I get the error message (ws is not defined).
app.get('/', function(req, res, next){
console.log('get route');
ws.send('message',"Hello world")
res.end();
});
Note : I need this to be socket based and not a normal API.
via puneeth8994
No comments:
Post a Comment