简体   繁体   English

具有HTTP服务器,WebSocket和Express的体系结构

[英]Architecture with http server, websocket and express

I'm trying to make a web site using NodeJs "http-server", "express" and "web socket". 我正在尝试使用NodeJs“ http-server”,“ express”和“ 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. 基本上,“ http服务器”正在侦听端口“ 8080”,在“ index.html”页面上,我有一个简单的表单来执行登录。

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. 实际上,我阅读了这篇文章( https://auth0.com/blog/2014/01/15/auth-with-socket-io ),并且正在尝试重现身份验证过程。 So I'm trying to create the "express" app to handle the "/login" route but, I have a port issue. 因此,我试图创建“ express”应用程序来处理“ / login”路由,但是,我遇到了端口问题。 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. 我无法收听“ http-server”所使用的端口“ 8080”,也无法收听其他端口,因为如果这样做,我对“ / login”路由的AJAX调用将被阻止通过CORS系统。

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. 我的目标非常简单:我想有一个提供html / css和javascript文件的网络服务器(因此是普通的网络服务器),但我也想有一个使用“ express”处理“代码”的“ NodeJs”模块登录和websocket用于其余的通信。 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. 我看到可以在同一端口上使用“ ws”和“ express”,但是我不知道如何通过网站启用AJAX登录。

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. 您可以通过在快速应用程序上设置Access-Control-Allow-Origin标头来在其他端口上托管快速应用程序,而不会遇到CORS问题。 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. 这样,您将为通过快速应用程序的每个请求设置标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM