I am first time experiencing socketio Admin UI. I am facing an issue, I m not abale to view all feature in dashboard. when i visit on https://admin.socket.io/#/ and after successfully login it just shows following menu.
here is my connection snippet.
const app = express();
const http = require('http');
const { instrument } = require("#socket.io/admin-ui");
const server = http.createServer(app);
var io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io"],
credentials: true,
},
});
instrument(io, {
auth: false
});
I want that all feature as shown in that menu.
Sockets
Rooms
Clients
Events
I found the answer. Actually default mode is development but somehow it was not set when i set the mode to development it works fine for me.
const app = express();
const http = require('http');
const { instrument } = require("#socket.io/admin-ui");
const server = http.createServer(app);
var io = require("socket.io")(server, {
cors: {
origin: ["https://admin.socket.io"],
credentials: true,
},
});
instrument(io, {
auth: false,
mode: "development"
});
reference : https://socket.io/docs/v4/admin-ui/#mode
Related
In development, this is how I was connecting to socket.io:
// server.js
const express = require('express')
const app = express()
const port = 8000
const server = app.listen(port, () =>
console.log(`Server is running on port ${port}`)
);
const io = require('socket.io')(server, {
path: '/socket.io',
pingTimeout: 60000,
cors: {
origin: 'http://localhost:3000',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-type'],
},
maxHttpBufferSize: 1e8,
});
// App.js
import io from 'socket.io-client';
let socket;
const App = () => {
useEffect(() => {
socket = io(
'http://localhost:8000/',
{ path: '/socket.io' },
{ reconnection: true }
);
}
})
It made sense that in production I should just need to change instances of localhost to my domain, however doing so gave me this error:
net::ERR_FAILED 200 (OK)
From research I learned this was a CORS error, so I then amended my domain in App.js to include the port :8000 but then that brings up this error:
net::ERR_CONNECTION_TIMED_OUT
My site in production is running on https and I have amended my domain in both instances accordingly. I have also enabled the uncomplicated firewall through my host. Hoping someone out there can help me to understand what the issue is.
I change from "const socketio = require("socket.io-client");" to "const socketio = require("socket.io");" but it is not working.
the third pic is Back-end and fourth is Front-end. it doesn't say the exact error is but "this.ws =" and "websocket.js:50 WebSocket connection to 'ws://localhost:8080/socket.io/?EIO=4&transport=websocket' failed: " is all.
you can check in https://socket.io/docs/v4/server-initialization/ i think it's:
io.on("connection",()=>{}) // on server side
if that doesn't work you can try to move all socket code before server.listen it would be something like this:
const http = require('http')
const { Server } = require('socket.io')
const app = require('./app')
const server = http.createServer(app)
const io = new Server(server, {
cors: {
origin: 'http://localhost:8080',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
},
})
io.on('connection', (socket) => {
console.log("socket",socket);
}
server.listen(process.env.PORT || 5000, () => {
console.log(`Listening on port ${process.env.PORT || 5000}`)
})
As outlined in the title, I am having difficulty setting a http cookie to be used for auth purposes when tunnelling using ngrok.
The following code works fine (obviously with the relevant endpoints specified) when i am running a query from from localhost to a localhost endpoint in my dev environment but breaks down as soon as i start to query the ngrok tunnel endpoint.
Frontend api query (simplified as part of larger application)
function fetchRequest (path, options) {
const endpoint = 'http://xxx.ngrok.io'; // the ngrok tunnel endpoint
return fetch(endpoint + path, options)
.then(res => {
return res.json();
})
.catch((err) => {
console.log('Error:', err);
});
}
function postRequest (url, body, credentials='include') {
return fetchRequest(`${url}`, {
method: 'POST',
withCredentials: true,
credentials: credentials,
headers: {'Content-Type': 'application/json', Accept: 'application.json'},
body: JSON.stringify(body)
});
}
// data to be passed to backend for authentication
let data = {pin: pin, username : username};
postRequest('/',data)
Express server on Node.js with ngrok tunnel (app.js)
const express = require('express')
const session = require('express-session')
const cors = require('cors')
const router = require('./router');
const tunnel = require('./ngrok')
const app = express()
const port = process.env.PORT || 4001;
app.use(cors({
origin: 'http://localhost:3000'
credentials: true,
}))
app.use(express.json());
const expiryDate = new Date(Date.now() + 60 * 60 * 1000) // 1 hour
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: expiryDate
// sameSite: 'none'
// secure: true
}
}))
app.use(router)
let useNGROK = true;
if (useNGROK) {
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
tunnel.createHTTPtunnel().then((url) => {
console.log(`New tunnel created with endpoint: ${url}`)
});
} else {
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
}
Ngrok configuration (ngrok.js)
const ngrok = require('ngrok');
const find = require('find-process');
const port = process.env.PORT || '3000';
const tunnel = {
createHTTPtunnel: async function () {
const list = await find('name', 'ngrok');
if (list.length > 0) {
let api = ngrok.getApi();
if (api == null) {
this.kill_existing_tunnel();
} else {
let open_tunnels = await ngrok.getApi().listTunnels();
return open_tunnels.tunnels[0].public_url;
}
}
let ngrok_config = {
proto: 'http',
bind_tls: false,
name: process.env.NGROK_NAME,
hostname: process.env.NGROK_CUSTOM_DOMAIN,
// host_header: 'rewrite',
authtoken: '',
region: 'eu',
};
return ngrok.connect({ ...ngrok_config, addr: port });
},
kill_existing_tunnel: async () => {
const list = await find('name', 'ngrok');
list.forEach((p) => {
try {
process.kill(p.pid);
console.log(`Killed process: ${p.name} before creating ngrok tunnel`);
} catch (e) {
console.log(e);
}
});
}
}
module.exports = tunnel;
** router & controller (router.js & controller.js respectively) **
*router.js*
const router = require('express').Router();
const example = require('./controller')
router.post('/', example.authenticate);
module.exports = router;
*controller.js*
async function authenticate (req, res) {
try {
res.send(JSON.stringify('trying to send cookie'))
} catch (e) {
console.log('Error', e)
res.sendStatus(500)
}
}
module.exports = {
authenticate
};
The following information is provided when inspecting the Set-Cookie response header in the network requests:
This Set-Cookie header didn’t specify a “SameSite” attribute and was defaulted to “SameSite=Lax” and was blocked because it came from a cross-site response which was not the response to a top-level navigation. The Set-Cookie had to have been set with “SameSite=None” to enable cross site usage.
Attempted fix 1//
If I add the following options to the cookie {sameSite: ‘none’, secure:true}, amend the ngrok config to set {bind_tls: true} and run https on my front end (using a custom SSL certificate as per the create react app documentation), and query the https tunnel, then no cookie is received in the response from the server at all (request is sent and response 200 is received but with no cookie).
Attempted fix 2//
I also tried to change the host_header option to rewrite in the ngrok config (to mirror a response from localhost rather than from ngrok) and this did not work.
Any help would be much appreciated as I have little experience and I am stuck!
My api has stopped working, previously it worked fine and as far as i am aware I have changed nothing. When i tested my endpoint i received an internal server error.
Here is a link to my hosted api https://frozen-scrubland-34339.herokuapp.com/api
I have just checked some of my other apis and none are working either, same message. it appears my code isnt the issue but postgres itself?
Any help on what to do would be appreciated
When i tried to npm run prod to re-push it to heroku i received: 'Error: The server does not support SSL connections'
Again this was never an issue previously when it worked.
I imagine i have changed something with heroku itself by accident?
app.js
const express = require("express");
const app = express();
const apiRouter = require("./routers/api-router");
const cors = require("cors");
const {
handle404s,
handlePSQLErrors,
handleCustomError,
} = require("./controllers/errorHandling");
app.use(cors());
app.use(express.json());
app.use("/api", apiRouter);
app.use("*", handle404s);
app.use(handlePSQLErrors);
app.use(handleCustomError);
module.exports = app;
connection.js
const { DB_URL } = process.env;
const ENV = process.env.NODE_ENV || "development";
const baseConfig = {
client: "pg",
migrations: {
directory: "./db/migrations",
},
seeds: {
directory: "./db/seeds",
},
};
const customConfigs = {
development: { connection: { database: "away_days" } },
test: { connection: { database: "away_days_test" } },
production: {
connection: {
connectionString: DB_URL,
ssl: {
rejectUnauthorized: false,
},
},
},
};
module.exports = { ...baseConfig, ...customConfigs[ENV] };
We are using CORS to allow all origins
app.use(cors());
server running on port 4000, and client running on 3000
here is my server.js code
const cors = require("cors");
const http = require("http");
const socketIO = require("socket.io");
app.use(cors());
const port = process.env.PORT || process.env.DEFAULT_PORT;
console.log("port: ", port);
app.listen(port, () => {
console.log(`App listening at ${port}...`);
});
const server = http.createServer(app);
const io = new socketIO(server, {
transports: ["websocket"],
});
React js code
constructor(props) {
super(props);
try {
this.socket = io("http://localhost:4000", { transport: ["websocket"] });
this.socket.on("Chat-event", data => {
console.log("socketdata", data);
});
} catch (error) {
console.log("hiterror", error)
}
}
I am continuously getting this error on the client side after allowing origin for all.
Access to XMLHttpRequest at 'http://localhost:4000/socket.io/?EIO=3&transport=polling&t=Mv-SSIc' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute
For socket.io version 3.x.x cors configuration has changed, I managed to fix it by adding options to the socket creation.
Tried on the version 2.x.x also and it worked.
const io = socketio(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}
});
Here is the resource https://socket.io/docs/v3/handling-cors/
Bonus: In case you encounter Bad Request make sure you have the same version of socket.io for the client and the server.
By following these steps you can get rid of these error.
// 1) on server side
const cors = require('cors');
const socketio = require('socket.io')
const http = require('http');
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: localhost:3000/, //your website origin
methods: ["GET", "POST"],
credentials: true
}
});
// 2) add these middlewares
app.use(cors())
app.options('*', cors());
// 3) on client-side
import io from 'socket.io-client'
let socket = io.connect(localhost:8080, { transports: ['websocket'] }) // your local server
try using the cors credentials config:
app.use(cors({credentials: true}));
Please allow all to socket.io at server side
const socketIO = require('socket.io')(server, { origins: '*:*'});
Or you can set socketIO origins as *
socketIO.set('origins', '*:*');
#user4860402 Gave me solution, thing is that by default npm is installing socket.io client v 2.X.X but on server I'm using latest verion (also provided by npm) 3.0.5
So all problems including 400 error comes because client and server verion doesnot match.
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const socketio = require("socket.io");
const cors = require("cors");
const io = socketio(http, {cors:{origin:"*"}});