I'm working with node.js and express.js, and I'm trying to add socket.io to one of my .ejs files but when I'm doing that I get some weird errors:
Failed to load resource: the server responded with a status of 404 (Not Found) socket.io/?EIO=3&transport=polling&t=MV6f2K2
Failed to load resource: the server responded with a status of 404 (Not Found) socket.io/?EIO=3&transport=polling&t=MV6f2cR
and then,per second :
GET https://www.mywebsite.eu/socket.io/?EIO=3&transport=polling&t=MV6f2cR 404 (Not Found) socket.io.js:7
There are my files:
app.js:
const fs = require('fs');
const express = require('express');
const app = express();
const http = require('http').Server(app);
const fileUpload = require('express-fileupload');
var io = require('socket.io')(http);
.....
var router = express.Router();
var pathView = __dirname + "/views/";
app.use(express.urlencoded({extended: true}));
app.use(express.json());
const listenPort = 8000;
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public', express.static('public'));
app.use('/scripts', express.static(__dirname + '/node_modules/'));
//SOCKET IO PART
io.on('connection', function(socket){
console.log('a user connected');
});
//SOCKET IO PART
..........
app.get & app.post requests
..........
app.use( "/", router);
// Not found
app.use("*",function(req,res){
res.setHeader('Content-Type', 'text/html');
res.status(404).send('Page introuvable !');
});
// Run server
app.listen(listenPort, function () {
console.log('Example app listening on port ' + listenPort )
})
profile.ejs:
.....content of the page(it's working well).......
<%- include('scripts') -%>
<script src="/scripts/socket.io/socket.io.js"></script>
</html>
<script>
var socket = io();
</script>
I have to mention that I copied the socket.io.js from socket.io-client and I put it into socket.io if I wouldn't have done that I would have got a 404 file missing error in devtools.
Hope the rest of the code is not required, I didn't add it because it was a lot and it has nothing to do with socket.io.
I think you should try and break it down a little bit to identify your problem. You are clearly not reaching your socket.
Try to have a server just like this:
var express = require('express')
var app = express()
var server = require('http').Server(app)
var io = require('socket.io')(server)
io.on('connection', function(socket) {
console.log('Socket did connect');
});
server.listen(8080)
And Client:
var socket = io();
If this works, which it very much should, try to add the rest of your code. Ejs shouldn't be the problem since it's compiled to regular HTML before it's served.
A problem would be if you have you client running on a different domain (or port) than the server. If so, you would have to define it inside the io() on the client site, eg: var socket = io("http://localhost:8080")
Related
I'm new to node.js and socket.io. They asked me to divide the connect4 game (I made with Javascript,node.js, express, socket.io, jquery ) into 2 separate apps (server app and client app).
The node.js of these two Apps must be connected to each other. In other words, I need to connect Client App's Node application to the port of the Server App's node application. (They said I should have 2 working ports belonging to 2 applications)
(Before divided the app it was working normal; when client give the url of the room he can play with his friend, game start and over normally But now everything mixed.)
Connect 4 game was working when client and server in the same App but now I cant do something like that
"
app.get('/:room([A-Za-z0-9]{9})', function(req, res) //app.set('view engine', 'html'); //res.status(200).sendFile(__dirname+'./index.html');
"
But my main problem is I couldn't connect from Client App nodejs to Server app nodejs .
Code part of the server app;
const express = require('express');
const cors = require('cors');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http ,{
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
serveClient: false,
pingInterval: 5000,
});
const port = process.env.PORT || 4000;
const { randomNumeric } = require('./utils.js');//I want random room key for later
// TODO: IF CORS DOES NOT WORK, TRY TO USE IT IN EXPRESS SERVER
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-HEADERS', 'Content-Type');
});
io.listen(port, () => { //Its not working :(
console.log("çalışıyor");
console.log(`Server started at ${port}`);
});
And Client App node.js code;
var express = require('express'),
game_logic = require('./game_logic'),
app = express(),
server = require('http').createServer(app),
port = Number(process.env.PORT || 3000);
server.listen(port);
console.log('Node.js web server port 3000 de çalıştı')
/*routing*/
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/img", express.static(__dirname + '/img'));
app.get('/', function(req, res) {
res.sendFile(__dirname+'/index.html');
});
And in Client App I have App.js for socket.io connect
$(function(){
var socket = io.connect(),
player = {},
yc = $('.your_color'),
oc = $('.opponent_color'),
your_turn = false,
url = window.location.href.split('/'),
room = url[url.length-1];
after that I have code for connect socket.io like socket.on and socket.emit
when I run this 2 App and open the local3000 I just saw empty game board nothing happened,
Can you help me about this and I really need to some links about this topic. Thank u
HER MY CODE IS :
IN app.js or SERVER CODE
var express = require("express");
var app= express();
var http = require("http");
var http = require("http");
var server= http.createServer(app);
var port = 5000 || process.env.PORT;
var socket= require("socket.io").listen(server);
var path = require("path")
app.use(express.static(path.join(__dirname+"/public")))
app.get("/", (req, res)=>{
res.sendFile(__dirname+"/index.html");
});
socket.on("connection", (socket)=>{
console.log("SOCKET IS CONNECTED")
})
server.listen(port, ()=>{
console.log(`connected at port no: ${port}`)
})
//IN INDEX.HTML
<script src="/socket.io/socket.io.min.js"></script>
<script src="/js/main.js"></script>
i have also tried
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script src="/js/main.js"></script>
//IN MAIN.JS
var socket = io("http://localhost:5000");
but getting this error :
VM554:5551 crbug/1173575, non-JS module files deprecated.
in network tab i got "FAILED TO LOAD RESPOND DATA"
and in this directory i could not find socket.io.js:
C:\Users\pc\Desktop\socket\back\node_modules\socket.io\client-dist
can anyone help me plzz i was trying to figure it out for 2 days
I am getting cross origin headers error despite running cors library, or simply a 404 not found while polling in the console.
The project structure looks like this
My goal is to have the little chat widget on every view. I will include this to the other views as EJS partial.
I am not sure what I going wrong I have tried to run Express on port 5000 and Socket IO on 8080 or 3000, all different combinations have not yielded anything good.
APP.JS looks like this
const { check } = require('express-validator');
const express = require("express");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const config = require("config");
const flash = require('express-flash');
const cookieParser = require('cookie-parser');
const nodemailer = require("nodemailer");
const Mailgen = require("mailgen");
const dotenv = require('dotenv');
dotenv.config();
const appController = require("./controllers/appController");
const isAuth = require("./middleware/is-auth");
const connectDB = require("./config/db");
const mongoURI = config.get("mongoURI");
const bodyParser = require('body-parser');
var cors = require('cors') // This should help, but does nothing
const app = express();
const http = require('http').Server(app); // I suspect the mistake is in these lines
const io = require('socket.io')(http,
{
cors: {
origin: "http://localhost:5000", // Does nothing
credentials: true
}})
connectDB();
const store = new MongoDBStore({
uri: mongoURI,
collection: "mySessions",
});
app.use(cors({origin: '*'})) // Also seems not to be working
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: true }));
//Middleware and Routes
io.sockets.on('connection', function(socket) {
console.log("hello") // never happened
socket.on('username', function(username) {
console.log("hello") // never happened
socket.username = username;
io.emit('is_online', '🔵 <i>' + socket.username + ' join the chat..</i>');
});
socket.on('disconnect', function(username) {
io.emit('is_online', '🔴 <i>' + socket.username + ' left the chat..</i>');
})
socket.on('chat_message', function(message) {
io.emit('chat_message', '<strong>' + socket.username + '</strong>: ' + message);
});
});
app.listen(5000, console.log("App Running on http://localhost:5000"));
And the front end partial EJS looks like this
<ul id="messages"></ul>
<form action="/" method="POST" id="chatForm">
<input id="txt" autocomplete="off" autofocus="on" oninput="isTyping()" placeholder="type your message
here..." /><button>Send</button>
</form>
The rest of the front end page looks like this
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style> etcetc
<%- include ('./partialChatWidget.ejs') %>
And the JS
<Script>
var socket = io.connect('http://localhost:5000', { transport : ['websocket'] } );
$('form').submit(function(e){
e.preventDefault();
socket.emit('chat_message', $('#txt').val());
$('#txt').val('');
return false;
});
socket.on('chat_message', function(msg){
$('#messages').append($('<li>').html(msg));
});
socket.on('is_online', function(username) {
$('#messages').append($('<li>').html(username));
});
var username = prompt('Please tell me your name');
socket.emit('username', username);
</script>
So what is going wrong here, do I need 2 servers on different ports or 2 instances, I always thought socket IO borrows the http server , not the express instance.
Thanks for helping me out. I might add I get the cross origin errors when I try to run on 2 different ports. Else I get 404 not found in the console. The page and the partial and the initial JS(Jquery) run.
After a lot of back and forth....
Just make sure to load the front end link for socket IO right in the head section asap.
And do include this part on the front end
var socket = io.connect('http://localhost:5000', { transport : ['websocket'] } );
Definitely include this on the server side, this cant hurt, unless you want to block some pages from CORS access
app.use(cors({origin: '*'}))
The next 2 steps made it all work.
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http,
{
cors: {
origin: "http://localhost:5000 {this is the port of your back end app, not for the socket IO port }",
credentials: true
}})
And finally, indeed, 2 servers.
const server = http.listen(8080, function() {
console.log('listening on *:8080');
});
app.listen(5000, console.log("App Running on http://localhost:5000"));
Took me a while, but now everything is clear once and for all(I hope)
app.use((req,res, next)=>{
res.setHeader('Access-Control-Allow-Origin',"http://localhost:3000");
res.setHeader('Access-Control-Allow-Headers',"*");
res.header('Access-Control-Allow-Credentials', true);
next();
});
use this code
and install the older socket.io version 2.3.0
try this code
`const server = app.listen(PORT,()=>console.log(`listening on port ${PORT}`));
io = require('socket.io').listen(server);
io.on('connection', (socket) => {
console.log('a user connected');
});`
Working with express Router for getting for the first time.
This is my route.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('home page');
});
module.exports = router;
This is my index.js
var express = require('express');
var app = express();
var router=require('./route.js');
app.use('/route',router);
var server = app.listen(process.env.PORT ||8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
});
When I open run it in browser it shows:
Cannot GET /
The only URL the code you have written will respond to is:
www.example.com/route/
If you want it to respond to:
www.example.com
then change to the following in your index.js file:
app.use('/', router);
You should replace
app.use('/route',router); with app.use('/', router);
As I may see you have created default route in app.use as /route
you must not have added that using app.use('/') would be enough instead of creating another route for that
Thanks.
I'm using socket.io over node.js, with Expressjs. When I serve up my html page, I have the socket.io.js file link hardcoded in a script tag:
<script src="/socket.io/socket.io.js"></script>
I'm not sure how to match that to my directory tree. It is as follows:
It resides buried down in the 'node_modules' folder.
My index.js looks like this:
const PORT = 3000;
const express = require("express");
const server = express();
const http = require("http").Server(server);
const path = require("path");
const io = require("socket.io")(http);
server.use(express.static(path.join(__dirname + "/public")));
server.use(express.static(__dirname + "/public/css"));
server.use(express.static(__dirname + "/public/js"));
server.listen(PORT, function() {
console.log("server listening on port " + PORT);
});
io.on("connection", function(socket){
console.log("user connected");
});
You only have to change server.listen to http.listen and it will work