I am developing a website that needs to catch events emitted from server.js into a javascript file that handles the frontend. Obviously I am using socket.io (i said that in the title) and the method I am using to connect the backend and the frontend is the following:
<script src="/socket.io/socket.io.js"></script>
<script src="js/chat.js"></script>
Then in the chat.js file i just decalre a const like this:
const socket = io();
and then I use the method
socket.on('event', (data) =>{
});
eccc...
This method does not seem to work though.
It says: Failed to load resource: the server responded with a status of 404 (Not Found).
(Also says that io is not defined but it's normal if it cannot find the socket.io file).
I have followed a tutorial that has done the same and it does not work anymore as well.
On my server.js the code looks like this:
const mongoose = require('mongoose');
const connectDB = require('./config/dbConnection');
const express = require('express');
const app = express();
const path = require('path');
const http = require('http');
const server = http.createServer(app);
const socketio = require('socket.io');
const io = socketio(server);
const fsPromises = require('fs').promises;
const bodyParser = require('body-parser');
const User = require('./model/user');
const moment = require('moment');
const PORT = process.env.PORT || 3500;
Thanks to anyone who answers.
Related
I have built a backend and wanted to test it with some front-end code but for whatever reason, it is just not firing the events on the server. I dont get the "on connect" event triggered. I already downgrade the backend to a version similar to my testing script but still all the server shows, are logs like this.
[22/Oct/2021:14:06:21 +0000] "GET /socket.io/?EIO=4&transport=polling&t=NoeKlFT&b64=1 HTTP/1.1" 404 149 "-" "node-XMLHttpRequest"
I am using socket io for server and client version 3.1.2
Here is the backend code snippet
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const morgan = require("morgan");
const cors = require("cors");
const config = require("./src/config/general");
const exchangeController = new ExchangeController(io); // I want to pass in the IO obejct to be able to deal with all the event stuff in another file besides the apps entry point file.
Here is the part where I want the IO object to be available and work with the events from there
class ExchangeController {
constructor(io) {
this.io = io;
this.exchangeService = new ExchangeService();
this.router = express.Router();
this.initRoutes();
this.io.on("connection", (socket) => {
console.log("incoming socket connection"); //gets never logged to console when connecting frontend
//do further stuff (deleted for post)
});
});
}
This is the frontend script for testing the connection
//client.js
const io = require('socket.io-client');
const socket = io("mysecreturl") //also tried localhost instead of deployed app url no difference
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
I really tried for way too long now without getting any results. I hope you guys can guide me on the right path again.
Cheers
I have HTML, CSS, and Javascript programs that work perfectly together. I've recently realized that I'm going to need a server to be able to complete some of my functionality. I've created a local Node server using some tutorials. After reading some suggestions, I'm trying to use Express to try to add the HTML, CSS, and Javascript to the Node, which are all in the same folder. The code I have (below) just causes the browser to stay on loading.
const http = require('http');
const fs = require('fs').promises;
const host = 'localhost';
const port = 8000;
var express = require('express');
var path = require('path');
var app = express();
const requestListener = function (req, res) {
app.use(express.static(path.join(__dirname, 'public')));
//res.writeHead(200);
//res.end("My first server!");
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
you don't need http module if you are using express...
const express = require('express')
const app = express()
// '/' is the url you want to host your site
// 'public' is the folder in which you have the necessary frontend files
// and the main html should be named as 'index.html' inside 'public'
app.use('/', express.static('public'))
app.listen(5000, () => console.log('server on port 5000'))
Try this....
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname,'css'));
app.use('/html',(req,res,next)=>{
res.sendFile(path.join(__dirname,'HTML','text.html');});
app.listen(3000);
I have a Nuxt App, with one service which needs to be delivered over WebSockets. The Nuxt App Server provides an api service using express.
I have an /api folder in which there are various *.js files, and these are routed to successfully. ie...
const express = require('express');
const app = express();
app.get('/whatever1',(req, res) => console.log('req.url',req.url))
works OK.
However the following, in the same file, will never be reached....
const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
app.ws('/whatever2',(ws,req) => {
console.log('req.url',req.url);
})
Where am I going wrong ?
You're attempting to connect the client to an endpoint on the server where no such endpoint exists. In your client's output, you're receiving an error of:
VM1295:1 WebSocket connection to 'ws://localhost:3000/api/whatever2' failed: Connection closed before receiving a handshake response
because you haven't defined a route of /api/whatever2. Your code above routes to:
ws://localhost:3000/whatever2
instead of ws://localhost:3000/api/whatever2
EDIT:
Here's test code that worked for me:
const express = require('express');
var app = express();
const expressWS = require('express-ws')(app);
expressWS.getWss().on('connection', function (ws) {
console.log('connection open');
});
app.ws('/whatever', (ws, res) => {
console.log('socket', ws);
});
app.listen(3000, () => console.log('listening on 3000...'));
I"m getting this message when I run mongod.
In the tutorial I'm doing, I think I should be getting something like "connection accepted from 127.0.0.16:6.."
I checked out this post already - mongod HostnameCanonicalizationWorker error on OS X
and I have my hosts file set up as such:
127.0.0.1 localhost
127.0.0.1 Bens-MacBook-Pro.local
255.255.255.255 broadcasthost
::1 localhost
These are my scripts for Node:
// Main starting point of the application
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
const morgan = require('morgan');
const router = require('./router');
const mongoose = require('mongoose');
// DB Setup
mongoose.connect('mongodb://localhost:auth/auth');
// App Setup
app.use(morgan('combined'));
app.use(bodyParser.json({type: '*/*' }));
router(app);
// Server Setup
const port = process.env.PORT || 3090;
const server = http.createServer(app);
server.listen(port);
console.log('Server listening on:', port);
This is the log for mongod:
2016-11-20T16:33:13.095-0700 I CONTROL [initandlisten] MongoDB starting : pid=15054 port=27017 dbpath=/data/db 64-bit host=Bens-MacBook-Pro.local
......
2016-11-20T16:33:13.380-0700 I NETWORK [initandlisten] waiting for connections on port 27017
What is missing?
Thanks!
UPDATED
http://code.runnable.com/UWxv-JS8trEHAACH/connect-to-mongodb-using-mongoosejs-for-node-js
I added a listener to check for connection:
/*
* More details here http://mongoosejs.com/docs/index.html
*/
//require mongoose node module
var mongoose = require('mongoose');
//connect to local mongodb database
var db = mongoose.connect('mongodb://127.0.0.1:27017/test');
//attach lister to connected event
mongoose.connection.once('connected', function() {
console.log("Connected to database")
});
And it is logging "Connected to database" so it appears to be connected even thought the mongod window says it's not. Let me go through the rest of the tutorial and see if it's truly connected.
You are making some errors
mongoose.connect('mongodb://localhost:auth/auth'); is looking for a port :auth that does not exist
const server = http.createServer(app); you can simply do app.listen(port);
router(app); you can simply do require('yourRouteFile.js')(app);
You should get it going with the following server.js
// Main starting point of the application
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const app = express();
const morgan = require('morgan');
const mongoose = require('mongoose');
const port = process.env.PORT || 3090;
// DB Setup
mongoose.connect('mongodb://localhost/auth');
// App Setup
app.use(morgan('combined'));
app.use(bodyParser.json({type: '*/*' }));
//Routes
require('yourRouteFile.js')(app);
// Server Setup
app.listen(port);
console.log('Server listening on:', port);
Ok. So i followed the rest of the node + mongoose tutorial and using postman, I was able to save stuff to the db, verified by Robomongo. But my log with mongod still says "waiting for connections on port 27017". So I am not sure why.....But things work.
my app.js is started with following code
var express = require("express"),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server),
games = require("./lib/games");
Now I need to use socket.io in external lib which named games,how can I do that?
There are many ways to do this. One way is to have games export a function which accepts the socket.io object as a parameter.
For example:
// games.js
module.exports = function(io) { ... /* do something with io */ }
// app.js
var io = require('socket.io').listen(server),
games = require("./lib/games");
games(io);