1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Works like a charm, thank you. And do you think it is a valid architecture or am I doing something too cumbersome ?
That is a valid architecture. I am using similiar one on my own project. Good luck with your project. :)
Cool thanks. One last question: How do you handle the fact that express is handling the web socket route ? I read about "express-ws" yesterday before going to sleep, it seems to be the solution, but maybe it exists something even simper ?
express-ws looks like a solid solution. By the documentation it seems to be easy to use. I haven't been using web sockets with express so I don't know if there is any better alternatives. But that should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.