ssougnez
ssougnez

Reputation: 5886

Architecture with http server, websocket and express

I'm trying to make a web site using NodeJs "http-server", "express" and "web socket". Basically, the "http-server" is listenning to the port "8080" and on the "index.html" page, I have a simple form to perform a login.

That's where I'm a bit stuck. Actually, I read this article (https://auth0.com/blog/2014/01/15/auth-with-socket-io) and I'm trying to reproduce the authentication process. So I'm trying to create the "express" app to handle the "/login" route but, I have a port issue. I can't listen to the port "8080" as it is used by the "http-server" and I can't listen to another port because if I do so, my AJAX call to the "/login" route will be blocked by the CORS system.

My goal is quite simple: I'd like to have a web server serving html/css and javascript files (a normal web server thus), but I'd also like to have a "NodeJs" module using "express" to handle the login and websocket for the rest of the communication. I saw that it's possible to use "ws" & "express" on the same port, but I have no clue of what I could do to enable to AJAX login via the web site.

Upvotes: 1

Views: 215

Answers (1)

Snekw
Snekw

Reputation: 2620

You can host the express app on other port and not run into the CORS issues by setting the Access-Control-Allow-Origin header on the express app. You can automaticly set it with following code:

app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'your origin here');
next();
});

That code needs to be before your route handling. That way you are setting the header for every request that goes trough your express app.

Upvotes: 2

Related Questions