HTTP Authorization Header in EventSource (Server Sent Events)

前端 未结 8 2009
梦谈多话
梦谈多话 2021-02-01 01:52

I need to set an Authorization header to an HTML5 EventSource. As Server Sent Events seems to be disused since Websockets appeared, I cannot find any useful documentation. The a

8条回答
  •  执念已碎
    2021-02-01 02:08

    The window.EventSource doesn't seem to support passing additional headers yet. Good news is there are some other implementations of EventSource that support additional headers. Some of them are as follows:

    • eventsource
    • event-source-polyfill
    const eventSource = new EventSource(resoureUrl, {
                headers: {
                    'Authorization': 'Bearer ' + authorizationToken;
                }
            });
    
    es.onmessage = result => {
        const data = JSON.parse(result.data);
        console.log('Data: ', data);
    };
    
    es.onerror = err => {
        console.log('EventSource error: ', err);
    };
    

提交回复
热议问题