最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Custom headers in EventSource connection - Stack Overflow

programmeradmin4浏览0评论

When I create a new EventSource in JavaScript to listen for server-sent events, like this:

var source = new EventSource("data/pushed");

Is there any way for me to specify additional headers (like some authentication token) in the outgoing HTTP request?

When I create a new EventSource in JavaScript to listen for server-sent events, like this:

var source = new EventSource("data/pushed");

Is there any way for me to specify additional headers (like some authentication token) in the outgoing HTTP request?

Share Improve this question edited Mar 25, 2016 at 20:08 Jean-Philippe Pellet asked Mar 24, 2016 at 13:27 Jean-Philippe PelletJean-Philippe Pellet 60k22 gold badges176 silver badges239 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

No, the EventSource standard does not include setRequestHeader the way XMLHttpRequest does.

It also does not support POST. But you do have cookies. So, my preferred approach for authentication tokens, where practical, is to have the user first login and create a session, and then that session cookie will be passed along with your SSE requests. (Aside: if using PHP, and using sessions with SSE, remember they are locked, so your SSE process should call session_write_close() as soon as it has validated the user. Sessions in other languages might have a similar issue.)

The only other alternative I can suggest is to use XMLHttpRequest (i.e. the Comet approach).

We had similar issue, and we decided in the end to send our authorization token through URL and not to worry about security since it will be protected by SSL (in production, of course, we use HTTPS protocol).

If you have flexibility to use other packages, can use ngx-sse-client which can be used to add headers. There are some other libs like eventsource which provides the same functionality

发布评论

评论列表(0)

  1. 暂无评论