Sending cookie from server to browser using express - javascript

I am a computer science student and have been working on login with express.js for hours on XAMPP but couldn't find solutions. Here's my idea.
A user types userid and password and sends it through the server using jquery post method. Then, the server will check if id and password match and will send a temporary cookie storing the userid so the browser knows who or status signed in. However, I can't send this cookie to the browser from the server. I would really appreciate your input on this code or my idea.
// Variables
var portNum = 3000;
var express = require('express');
var app = express();
var http = require('http');
app.post('/login',function (req, res) {
console.log("LOGIN");
res.cookie('test', 'testValue');
res.send();
})
var server = app.listen(portNum, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
})

Related

What do I replace "http://localhost:3000" with when using a server and not local machine?

I've been doing a lot of online courses with node and express. I want to get sockets.io to work but I can't even establish a connection at the moment. I am using a cPanel virtual private server and running code in the server terminal and then trying to use a website hosted on the server to access the .js file running on the server.
I've tried all sorts of different things but I'm reducing it to its most basic level to try get a connection. All the videos I've seen are running on a local machine and using the command prompt on a local machine to run the .js file and the browser to access http://localhost:3000.
The .js file I'm running on my cPanel server looks like this;
var express = require('express');
var app = express();
app.get('/', function(req,res){
res.send('Hello world 2');
})
app.listen(3000);
So how do I then access that via the browser? I have tried http://mywebsite.com:3000 and http://11.22.33.444:3000 if 11.22.33.444 is the server ip, but the browser just times out and there is no output in the server console.
ultimately I need to run a socket.io command that looks like this;
var socket = io.connect('http://localhost:3000');
and in all the tutorials I've seen they use this localhost:3000 but no one explains how to access this if its on an actual server so I'm pretty lost.
There are other examples like;
...
const http = require('http').createServer();
...
http.listen(3000 => () => {
console.log('listening on port 3000');
});
That's just a snippet of the code but I'm wondering how I then access that 3000 port from the browser without http://localhost:3000
IF you read the docs you will see that there is a guide how to connect it with express: https://socket.io/docs/
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
// WARNING: app.listen(3000) will NOT work here!
app.get('/', function (req, res) {
res.status(200).json({ message: "Connected" });
});
io.on('connection', function (socket) {
console.log("somebody connected");
});
Think I just solved it. I tried a different port and it worked :/
No need to specify any address in io.connect()
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
http.listen(process.env.PORT || 3000, function() {
});
<script src="/socket.io/socket.io.js"></script>
var socket = io.connect();

Client unable to connect to server with socket.io

I'm having trouble with being able to connect to my node.js server from an external domain. It works fine when running it locally using the http web server through node however when connecting externally, it loads the socket.io.js file just fine but when trying to use the socket it removes the port from the URL and cannot connect.
Instead of doing this in the network requests:
http://external-domain.com:3000/socket.io/?EIO=3&transport=polling&t=M06GOUU
it does this:
http://external-domain.com/socket.io/?EIO=3&transport=polling&t=M06GOUU
I'm not sure how to make it not remove the port from the connection. How do I go about fixing this?
SERVER
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const publicPath = path.join(__dirname, '../public');
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(express.static(publicPath));
server.listen(3000, () => {
console.log(`Server is up on port 3000`);
});
CLIENT SCRIPT TAG
<script src="http://external-domain.com:3000/socket.io/socket.io.js"></script>
CLIENT JS ON A DIFFERENT DOMAIN
var socket = io();
socket.connect('http://external-domain.com:3000');
socket.on('connect', function () {
console.log('Connected to server.');
});
Change from this:
var socket = io();
socket.connect('http://external-domain.com:3000');
to just this:
var socket = io("http://external-domain.com:3000");
And, you don't use the socket.connect() as you will already have requested the connection with the io("http://external-domain.com:3000"); call.
Explanation
The code:
var socket = io();
uses the page URL to connect to a socket.io server at that origin. That is not what you want (apparently).
If you wanted to use the .connect() method, it would be like this:
var socket = io.connect("http://external-domain.com:3000");
Note: var socket = io(url) is simply a shortcut for var socket = io.connect(url).
socket.connect() does not accept a URL as a parameter so you simply weren't using that correctly. It's just a synonym for socket.open().
Use io.connect("url")
var socket = io.connect("http://external-domain.com:3000", { rejectUnauthorized: false });
// { rejectUnauthorized: false } is an optional parameter.
Hope this works for you.

Make a cookie when a user connects with socket. io - node js

have a server that uses socket.io. When a user connects it will assign them the user id thats made on the server then increment it by 1 so the next user with have a different id.
I want to use cookies for this, to check if they have previously logged in, if so, use that id, if not, use the one on the server.
the way to create a cookie is by using
res.cookie('cookie', 'monster')
but im not where i would put it, i tried putting it in the connect function but res wouldnt exist. and if i put it outside the function, how would i call it? Here is my code. This is the start of my server:
//Require npm modules
var express = require('express');
var http = require('http');
var events = require('events');
var io = require('socket.io');
var ejs = require('ejs');
var app = express();
//Set the default user Id to 1 and the default username to Guest
exports.Server = Server = function()
{
this.userId = 1;
this.userName = "Guest";
};
app.set('view engine', 'ejs');
app.get('/game/:id', function (req, res)
{
res.render('game', {game: req.params.id});
});
Server.prototype.initialise = function(port)
{
//Create the server using the express module
this.server = http.createServer(app);
//Declare the 'public' folder and its contents public
app.use(express.static('public'));
//Listen to any incoming connections on the declared port and start using websockets
this.server.listen(port);
this.startSockets();
this.em = new events();
consoleLog('SERVER', 'Running on port: ' + port);
};
Server.prototype.startSockets = function()
{
//When a user connects to the server on the 'game' socket
this.socket = io.listen(this.server);
this.socket.of('game').on('connection', function(user)
{
res.cookie('cookie', 'monster')
//Set their usedId and username
user.userId = this.userId;
user.userName = this.userName + " " + this.userId;
//Increment the user id by 1 so each user with get a unique id
this.userId++;
//Send a response back to the client with the assigned username and user id and initialise them
user.emit('connected', user.userId, user.userName);
this.em.emit('initialiseUser', user.userId, user.userName);
So where i have the res.cookie is where i want to be able to read and write cookies, any help is appriciated
I think what you are looking for is the middleware pattern employed by express. You can define as many of these middleware calls as you wish, and they are the perfect scope for calling any other functions which may need the res instance (or the req instance for that matter).
app.use(function (req, res, next) {
// call function, passing in res here
next();
})
Reference: https://expressjs.com/en/guide/using-middleware.html
EDIT:
This answer is not correct for your situation. In a node/express server not using socket connections, then yes, you could easily use the above pattern anywhere you need the request and response objects in scope.
However, once you setup the socket io server, the game changes. During the socket communications, there are no express request and response objects in scope anymore, everything is handled directly between your socket handling code and the client. So the answer is you need to handle the situation in a socket io way, not in an express way.
Please see: Adding a cookie value on Socket.IO

400 bad request (making game with node and socket.io)

Making a game, I have no idea what I am doing when it comes to the online aspect.
I am using node.js using my computer as the server host and client (localhost:3000)
var express = require('express'); //no idea what I am doing here
var app = express();
var server = app.listen(3000);
var socket = require("socket.io");
var io = socket(server);
io.sockets.on('connection', newConnection);
app.use(express.static("public"));
console.log("server is up"); //tells me that the server is ready
function newConnection(socket) {
console.log("new player!", socket.id); //tells me when a new player connects.
}
also have this code within the main public javascript file
var socket;
socket = io.connect("localhost:3000");
Whenever a new player connects i get 400 bad request errors and the game thinks multiple players have joined.
picture to aid
so pls help.
You will need to handle what happens when someone connects to your server.
var express = require('express');
var app = express();
var server = require("http").createServer(app);
server.listen(3000) //server listens on port 3000
var io = require("socket.io")(server)
//this will be called when a new client connects
io.on("connection", (socket)=>{
//socket is the socket object of the new client
console.log("new socket connected with socket id = " + socket.id)
})
Look at socket.io docs for more info.
In my game, I had a constructor function called "Number" and that was causing the problem the entire time.
I'm assuming that the socket.io or node.js already had a function called "Number" and that's what caused the problem.

Socket.io trigger events between two node.js apps?

I have two servers, one for the back end app, and one that serves the front end. They are abstracted, but share the same database, I have a need for both to communicate real time events between each other using socket.io.
Front end
// serves a front end website
var appPort = 9200;
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
socket.on('createRoom', function(room) {
socket.join(room); // use this to create a room for each socket (room) is from client side
});
socket.on('messageFromClient', function(data) {
console.log(data)
socket.broadcast.to(data.chatRoom).emit('messageFromServer', data);
});
});
Back end
//Serves a back end app
var appPort = 3100;
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
socket.on('createRoom', function(room) {
socket.join(room); // use this to create a room for each socket (room) is from client side
});
socket.on('messageFromClient', function(data) {
console.log(data)
socket.broadcast.to(data.chatRoom).emit('messageFromServer', data);
});
});
As an admin I want to log in to my back end where I can see all the people logged in, there I can click on whom I would like to chat with.
Say they are logged in to the front end website, when the admin submits a message client side they trigger this socket.emit('messageFromClient', Message); how can I trigger messageFromClient on the front end using port 9200 submitting from the backend port 3100?
You really dont need to start the socket.io server in the front end for this use case.
The way you can get it to work is :
Keep the backend as it is, which acts as a Socket.IO server
In the font end connect to the server using a Socket.IO client.
You can install the client by calling
npm install socket.io-client
and then connect to the server using :
var io = require('socket.io-client'),
socket = io.connect('localhost', {
port: 3100
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('messageFromClient', { user: 'someuser1', msg: 'i am online' });
You can then create a map of socket objects with their corresponding username and send a message to that user based on your business logic.
More Information :
You may have to add cases like client disconnection etc. You can read more about the call backs for that here :
https://github.com/Automattic/socket.io-client

Categories

Resources