Why can't I see cookie value in a WebSocket handshake request header?

Viewed 1828

I wanted to send a websocket handshake request from an html page and wrote codes like below:

  document.cookie = "guestId=xxxx; remember=xxxxxx;";
  var ws = new WebSocket("ws://localhost:5000/ws");

But what shown in Chrome Dev Tools appears that no cookie was sent:

General:
  Request URL:ws://localhost:5000/ws
  Request Method:GET
  Status Code:307 Temporary Redirect
Response Headers
  Content-Length:59
  Content-Type:text/html; charset=utf-8
  Date:Fri, 18 Mar 2016 09:39:11 GMT
  Location:/preorder/landing/index
Request Headers
  Accept-Encoding:gzip, deflate, sdch
  Accept-Language:en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
  Cache-Control:no-cache
  Connection:Upgrade
  Host:localhost:5000
  Origin:http://localhost:63342
  Pragma:no-cache
  Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits
  Sec-WebSocket-Key:t3N0vVaLCsOmOXLSh+Arsw==
  Sec-WebSocket-Version:13
  Upgrade:websocket
  User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36

How can I fix this? Why there is no cookie in request headers? If I send other ajax request not upgraded, I can see cookies in Dev Tools. Why is there such differences?

2 Answers

Your Origin header is http://localhost:63342 and the WS request is to ws://localhost:5000/ws so your domains are different (different ports). I imagine your other ajax requests are to http://localhost:63342 and thus the browser sends the cookie.

Related