Sending acknowledgements with socket.io, says my function is undefined - javascript

I am trying to use acknowledgements with socket.io as defined in http://socket.io/#how-to-use "Sending and getting data (acknowledgements)".
My client code looks like
sio.emit('ferret', 'tobi', function (data) {
console.log(data);
});
And my server code is:
socket.on('ferret', function (name, fn) {
fn('woot');
});
But I'm getting an error that's crashing my node server:
fn('woot');
23:13:48 web.1 | ^
23:13:48 web.1 | TypeError: undefined is not a function
Which I find strange because if I add:
console.log(name);
console.log(fn);
, name will log Tobi, but for what ever reason fn is logging undefined.
Any information would be awesome!!

In case anyone was having this problem, make sure that on the client, the emit has an acknowledgement function as the last parameter. If you write the server side code and restart the server again, it will give an error unless you have the client side page refreshed with the new code. Although I had written the code on both client and server, I kept getting the error on my server because I had not refreshed my client side page.

Related

http-proxy-middleware econnreset error after successful post request

Developing a contact form using Nodejs/Express and create-react-app following this tutorial https://www.youtube.com/watch?v=o3eR0X91Ogs. The issue that I'm running into is that when I hit submit on the form the message succeeds, and I get it in my inbox. However, in the developer console, I am hit with the timeout error I set on the axios.post located in Contact.js, and in my terminal it logs message sent, console log located in index.js, immediately throwing the following error afterward:
HPM ERROR: Error: socket hang up
[1] at connResetException (internal/errors.js:612:14)
[1] at Socket.socketCloseListener (_http_client.js:443:25)
[1] at Socket.emit (events.js:326:22)
[1] at TCP.<anonymous> (net.js:673:12) {
[1] code: 'ECONNRESET'
[1] }
[1] [HPM] Error occurred while trying to proxy request /api/contact/ from localhost:3001 to http://localhost:3000/ (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
Does anyone know why this error is occurring, and how I can fix it? The message sends but hangs afterward which prevents the app state from resetting (resetForm). At the same time, the axios.post in Contact.js doesn't update the state of sent to true.
The Github repo for the project.
Edit: I've been stuck on this for a few days now. Looked at similar questions, attempted ALL the fixes I could find, and this error still persists.
This is a common misunderstanding about how ExpressJs responses work. If you don't send a response to the request, it'll be stuck forever. So all you have to do is to send a response! Also, the res variable was re-defined in the callback of sendMail function. Here is the fix:
app.post('/api/contact', (req, res) => {
// ...
smtpTransport.sendMail(mailOptions, (err, mailResponse) => {
if(err) {
console.log(err);
} else {
console.log('Message sent!');
}
smtpTransport.close();
return res.send(err ? err : 'Message sent!');
});

How to know if a connection error occurred when using thrift from a javascript client?

I'm running the following thrift javascript client code. If the server is down, I don't get any error in the callback - just console log message.
How do I know if there're connection issues if the callback isn't invoked?
Javascript thrift client code:
var transport = new Thrift.Transport("/api/thrift/");
var protocol = new Thrift.Protocol(transport);
var client = new ApiClient(protocol);
client.doSomething(function (result) {
// Never invoked if the server is down.
});
Console log message:
POST http://localhost:81/api/thrift/ net::ERR_CONNECTION_REFUSED

NodeJS Sockets Sometimes Working

So, I have a node server, running expressjs io (uses socket.io), and I'm building a grid map that tracks coordinates in a database.
Only, I've run into a peculiar issue in that my sockets only listen sometimes.
At first there was no error message, and only by chance I let the page run and I got this error.
Uncaught TypeError: Cannot call method '0' of undefined UkPS99A_w96Ae0K570Nt?t=1395276358213&i=0:1
When I click on the file UkPS99A_w96Ae0K570Nt?t=1395276358213&i=0:1 I get this code:
io.j[0]("8::");
If I refresh the page, every few times it will suddenly work find for about 10 tile clicks, and then it stops working. My database is updating properly until the sockets basically die out.
Here is where I send the coordinates in my map:
io.emit("move", {x:this.x,y:this.y});
Server listening:
app.io.route('move', function(req) {
con.getConnection(function(err){
if (err) console.log("Get Connection Error.. "+err);
//removed query because redundant
req.io.emit("talk", {x:req.data.x,y:req.data.y});
});
});
and my socket script:
io.on("talk",function(data) {
console.log(data.x,data.y);
});
My script includes are at the bottom of the page in this order:
<script src="socket.io/socket.io.js"></script>
<script>io = io.connect();</script> <!-- open the socket so the other scripts can use it -->
<script src="../js/sock.js"></script>
<script src="../js/map.js"></script>
Is there something I'm doing wrong to that the socket seems to lose connection and throw some sort of error?
Update: I left the server running longer and a couple more error messages popped up in my console:
Uncaught TypeError: Cannot call method 'close' of null socket.io.js:1967
Uncaught TypeError: Cannot call method 'close' of null socket.io.js:1967
Uncaught TypeError: Cannot call method 'onClose' of null
More update: altered the connection line and added the proper CORS to my server.js
io = io.connect('http://sourceundead.com', {resource : 'socket.io'});
Still the same issue.
You seem to have a connection attrition as you never release them to the pool.
Assuming con is the (bad) name of your pool, instead of
app.io.route('move', function(req) {
con.getConnection(function(err){
if (err) console.log("Get Connection Error.. "+err);
//removed query because redundant
req.io.emit("talk", {x:req.data.x,y:req.data.y});
});
});
you should have something like
app.io.route('move', function(req) {
con.getConnection(function(err, connection){
if (err) console.log("Get Connection Error.. "+err);
//removed query because redundant
req.io.emit("talk", {x:req.data.x,y:req.data.y});
connection.release();
});
});
Be careful that using connections must be done with care to ensure they're always released, and it's a little tedious to do especially when handling errors as soon as you have a few queries to do when doing a task.
At some point you might want to use promises to make that easier. Here's a blog post about using bound promises to ease database querying in node.js.

SignalR not hitting OnConnected and giving Newtonsoft.Json.JsonReaderException

I am trying to setup SignalR at my ASP.NET MVC site and a Javascript client.
This is my client:
#section scripts{
<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<script type="text/javascript">
$(function () {
var connection = $.connection('/MY_ENDPOINT');
connection.received(function (data) {
$('#chatArea').append('>>' + data + "\r\n");
});
connection.start().done(function () {
$("#send").click(function () {
connection.send($('#msg').val());
$("#msg").val("");
});
});
connection.error(function (e) {
console.log(e);
});
});
</script>
}
Of course, I have the corresponding HTML elements chatArea and msg. In server, here is what I did:
Installed SignalR (latest version currently, 2.0.2) through NuGet.
Added app.MapSignalR("MY_ENDPOINT", new Microsoft.AspNet.SignalR.HubConfiguration()); in startup configuration, made sure it is called before registering auth methods.
I've subclassed PersistentConnection and overridden OnConnected and OnReceived methods.
However, when I run my app and navigate to the page, I can see that my endpoint's negotiate and connect methods are called, they both return OK (HTTP 200). I try to send anything using the webpage by clicking the "send" button, and at the server side I'm getting this error:
A first chance exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Additional information: Unexpected character encountered while
parsing value: a. Path '', line 0, position 0.
What could be the cause of this error?
UPDATE: I also have an iOS app with the SignalR-ObjC framework, and I can connect. However, when I try to send any data over it, I'm getting:
2014-03-06 19:39:39.853 Tanisalim[54987:70b] Websocket error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: internal server error (500)" UserInfo=0xade84e0 {NSErrorFailingURLKey=http://10.211.55.3/api/socket/send?transport=longPolling&connectionData=(null)&connectionToken=xybYQ8ItTN0IWUbyrosuHy%2F3jN0krIyHLO6b6Gq8VdC3orwRRGkVSIgtYkNQINVLhRMW77cX%2BU2LiHxoe0eDE3ZumT7JrObJcQ%2FXyHiP25%2BQy%2BZizHEHbsPyBBomERoI, NSLocalizedDescription=Request failed: internal server error (500), NSUnderlyingError=0xade1290 "Request failed: unacceptable content-type: text/html"
Still, no server-side breakpoints are hit.

Simple #meteor subscribe call giving an error

Server :
Meteor.publish('trades', function() {
return Trades.find();
});
Client:
Meteor.subscribe("trades");
Both:
Trades = new Meteor.Collection('trades');
When I run meteor, its giving me
TypeError: Object # has no method 'subscribe'
Any suggestions?
You might have your client code running in the root directory /. It would also then execute on the server and give this error. (Not sure if its this).

Categories

Resources