我正在制作一个聊天程序。
我正在使用 Nginx 服务器和 NodeJS。
我已经通过 ssl 设置了一个 websocket 并且工作正常。
我决定使用 cookie 进行身份验证。
有两个重要的功能:
mconnection.prototype.make_server_https=function(){
console.log('Make server https');
var cthis=this;
var server_https=modules.https.createServer({
key: this.ssl_key,
cert:this.ssl_cert,
ca:this.ssl_ca
},(request,response)=>{
console.log('### CreateServer ###');
console.log('CreateServer, Request:');
console.log(request);
console.log('CreateServer, Response:');
console.log(response);
console.log('######');
和
mconnection.prototype.make_server_websocket=function(){
var server_websocket=new modules.ws.Server({server:this.server_https});
var cookie = require("cookie");
var cthis=this;
//whenever a new client connects with the server.
server_websocket.on('connection', function(client_socket, request){
console.log('### On Connection ###');
console.log('OnConnection, Client Socket:');
console.log(client_socket);
console.log('OnConnection, Request:');
console.log(request);
console.log('######');
如果我做在客户端 url 中声明端口号,
函数 make_server_https 将运行并且在其中我可以访问 cookie 并通过响应对象设置它。
但在原始 url 中,
函数 make_server_websocket 运行,并且我可以访问服务器上的 client_socket。但是我似乎没有访问cookies。
我需要 client_websocket 来启动与这个给定客户端的连接。我需要以某种方式将它与 cookie 登录信息联系起来。
但我从来没有同时拥有这两者,所以我不知道如何连接它们以进行登录。
我可能误解了一些东西,我们将不胜感激在正确方向上的任何帮助。
最佳答案
您必须使用 GET
从 Node 服务器为您提供索引页面,然后当请求到达后端时,您将拥有响应对象,然后可以将其用于 SET-COOKIE
如果不是从后端设置的。
GET请求完成后,浏览器会添加COOKIE
,下次请求websocket连接时,COOKIE
会添加到REQUEST请求中浏览器的 HEADERS
将通过请求对象在后端可用。
如果您决定在登录系统中使用它,那么您可以在成功登录后SET-COOKIE
。
关于javascript - 将客户端套接字连接到 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64442793/