使用socket.io-client发送cookie [英] Send cookies with socket.io-client
问题描述
我正在尝试连接到网络套接字.我想通过实际的网站登录信息添加cookie,因此服务器(不我的服务器)知道我是谁(事件是特定于帐户的).
I am trying to connect to a websocket. I would like to add cookies from the actual website login, so the server (which is NOT mine), knows who I am (events are account specific).
var opts = {
extraHeaders: {
'Cookie': "_ga=GA1.2.17432343994.1475611967; _gat=1; __cfduid=dc232334gwdsd23434542342342342475611928"
},
}
function socket() {
var socket = io(websiteURL, opts);
var patch = require('socketio-wildcard')(io.Manager); patch(socket);
socket.on('connect', function () {
console.log(" > [Connected]");
});
socket.on('*', function (data) {
console.log(" >>> " + data);
});
socket.on('disconnect', function () {
console.log(" > [Disconnected]");
});
}
由于我正在从网站(而不是按帐户)接收公共事件,因此连接本身可以正常工作.
The connection itself works fine, since I am receiving the public events from the website (not per-account ones).
我尝试使用node-inspector查找问题.
I tried to find the problem using node-inspector.
这是正在执行的第一个请求.似乎请求标头为空,而那里缺少cookie.
This is the first request that is being done. It seems like the request headers are empty and the cookies are missing from there.
节点检查器:
该网站在chrome中的常规用法:
Normal usage of the website in chrome:
(是的,我在节点中发送的cookie较少,只是为了查看它们是否在请求cookie中弹出)
(Yes, I am sending less cookies in node, just to see if they pop up in the request cookies)
我做错什么了吗?我将如何以正确的方式添加Cookie?
Am I doing something wrong? How would I add cookies the right way?
推荐答案
我有一个类似的问题,我认为您的选项必须为轮询"传输方法设置cookie,如下所示:
I had a similar problem, I think your options have to set the cookie for the "polling" transport method, like this:
var opts = {
transportOptions: {
polling: {
extraHeaders: {
'Cookie': '_ga=GA1.2.17432343994.1475611967; _gat=1; __cfduid=dc232334gwdsd23434542342342342475611928'
}
}
}
}
我将其与以下多合一服务器-客户端示例一起使用:
I got this to work with the following all-in-one server-client example:
const express = require('express');
const http = require('http');
const app = express();
const httpServer = new http.Server(app);
const socketServer = require('socket.io')(httpServer);
const LISTEN_PORT = 4444;
socketServer.on('connection', socket => {
const cookieString = socket.handshake.headers.cookie;
console.log('server connection ' + (cookieString || ''));
setInterval(() => socket.emit('ping', Date.now()), 1000);
});
let socketClient = undefined;
httpServer.listen(LISTEN_PORT, 'localhost', () => {
console.log('web server started')
const options = {
transportOptions: {
polling: {
extraHeaders: {
'Cookie': 'hello=world'
}
}
}
}
socketClient = require('socket.io-client').connect('http://localhost:'+LISTEN_PORT, options);
socketClient.on('ping', (data) => console.log('ping ' + data));
});
这篇关于使用socket.io-client发送cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!