Simple #meteor subscribe call giving an error - javascript

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).

Related

TypeError: 'get binaryType' called on an object that does not implement interface WebSocket

Hello, some time ago, i started to make a userscript (tampermonkey script) where i get the active websocket, i have tried to get the websocket when the websocket send a message:
let ws;
window.WebSocket.prototype.send = function(){
if(!ws) {
ws = this
console.log(ws)
}
}
but not working, so i tried to handle messages but nothing showing up when a message was received:
let ws = window.WebSocket;
ws.onmessage = function(msg){
console.log(msg.data)
}
Finally i choosed to get websocket binaryType for reproduce it, but when i send
window.WebSocket.prototype.binaryType
in devtools, i got this error
(in latest Firefox)
TypeError: 'get binaryType' called on an object that does not implement interface WebSocket.
(in latest Microsoft Edge)
TypeError: Illegal Invocation
(i'm not good with English sorry, i'm French)
Thanks for answers
Thanks for answer, i have edited my script, code here:
let ws;
unsafeWindow.WebSocket.prototype.oldSend = unsafeWindow.WebSocket.prototype.send
unsafeWindow.WebSocket.prototype.send = function(m) {
if(!ws) {
ws = this
alert(ws)
}
unsafeWindow.WebSocket.prototype.oldSend.apply(this, [m])
}
//need that for get the websocket
unsafeWindow.WebSocket.prototype.send("ping")
This is working, i get the websocket but, i got an error:
TypeError: Illegal Invocation at WebSocket.unsafeWindow.WebSocket.prototype.send
what should i do?
[UPDATED!]
Line Error:
unsafeWindow.WebSocket.prototype.oldSend.apply(this, [m])
was called on the WebSocket object, not in the window.
Juste need to replace .apply to .bind
Corrected Line:
unsafeWindow.WebSocket.prototype.oldSend.bind(unsafeWindow, m)

Accessing part of a URL via JavaScript, but not preceded by question mark

I'm building a React web app, where I want to use the query from a URL to search a MongoDB Database, and find an entry by its ID.
I have the following example URL:
www.examplewebsite.com/:id
In practice, the example URL would look like this in the browser:
www.examplewebsite.com/5f8da21ba227e300076c3299
Using JavaScript, how would I access the id (5f8da21ba227e300076c3299) from that URL?
I figured I may be able to do something like this...
const queryString = window.location.search;
console.log(queryString)
// 5f8da21ba227e300076c3299
However, since the ID is not preceded by a query question mark, I'm guessing that wouldn't work...
I could use a hacky approach of adding a '?' after the URL perhaps in my Router (this is for a React web app), however not sure that would be consistently the best approach.
Does anyone have any tips?
EDIT: I've added the suggestions below into my serverless function, and tried to log the result. Here's my code:
module.exports = async (req, res) => {
let urlOne = window.location.pathname.split('/').pop();
let urlTwo = window.location.pathname.split('/');
console.log(urlOne);
console.log(urlTwo);
};
It's returning the following error however when I call the function:
2020-10-23T10:23:37.878Z 91f31b36-0986-44a1-a7d1-fbd31e066ea6 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"ReferenceError: window is not defined","reason":{"errorType":"ReferenceError","errorMessage":"window is not defined","stack":["ReferenceError: window is not defined"," at module.exports (/var/task/api/fetchEditDebt.js:12:16)"," at Server.<anonymous> (/var/task/___now_helpers.js:813:19)"," at Server.emit (events.js:315:20)"," at parserOnIncoming (_http_server.js:790:12)"," at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: ReferenceError: window is not defined"," at process.<anonymous> (/var/runtime/index.js:35:15)"," at process.emit (events.js:327:22)"," at processPromiseRejections (internal/process/promises.js:209:33)"," at processTicksAndRejections (internal/process/task_queues.js:98:32)"]}
Unknown application error occurred
You can use:
window.location.pathname.split('/')

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.

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

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.

Node js + Sails js + websocket app crashing every few hours

I am having a problem similar to socket.io issue using sails.js. Every once in a while (once per day, or even few hours, it varies), a visitor to the web site/app will crash Node, seemingly due to the way his websocket client tries to connect. Anyway, here's the crash log:
debug: Lowering sails...
/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:216
return 0 == str.indexOf('s:')
^
TypeError: Cannot call method 'indexOf' of undefined
at exports.parseSignedCookie (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:216:19)
at Manager.socketAttemptingToConnect (/Volumes/Two/Sites/lsdfinder/node_modules/sails/lib/hooks/sockets/authorization.js:35:26)
at Manager.authorize (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:910:31)
at Manager.handleHandshake (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:786:8)
at Manager.handleRequest (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:593:12)
at Server.<anonymous> (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:119:10)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2076:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
at Socket.socket.ondata (http.js:1966:22)
9 Oct 10:42:24 - [nodemon] app crashed - waiting for file changes before starting...
In config/sockets.js, authorization is set to true. Not sure what else to do, where to fix this. Any suggestions? I can read the Sails docs too, but this appears to be a problem in Express/Connect, no? Thanks.
...René
The problem is that once every so often, a client will connect that has no cookies. Sails.js is using util.parseSignedCookie() from Connect without checking for errors, and therefore an error is thrown. This is what it looks like in Sails:
if (handshake.headers.cookie) {
handshake.cookie = cookie.parse(handshake.headers.cookie);
handshake.sessionID = parseSignedCookie(handshake.cookie[sails.config.session.key], sails.config.session.secret);
}
If you take a look into the cookieParser() middleware of Connect, you can see error checking is required:
if (cookies) {
try {
req.cookies = cookie.parse(cookies);
if (secret) {
req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
req.signedCookies = utils.parseJSONCookies(req.signedCookies);
}
req.cookies = utils.parseJSONCookies(req.cookies);
} catch (err) {
err.status = 400;
return next(err);
}
}
I've created a Gist here that fixes the problem, and will submit a pull request to Sails.js when I have the time. The Gist uses Connect's cookieParser() middleware to automatically handle errors. If you want to use this, modify this file in your modules folder:
node_modules/sails/lib/hooks/sockets/authorization.js
If you are doing a crossdomain request, you could turn off authorization.
In *site_dir/config/sockets.js* set authorization to false. One way of doing it. You can also call your api with something like this
bash
**http://localhost:1337?cookie=smokeybear**
Its is in the comments on the sockets.js file.

Categories

Resources