new EventSource 不可以设置请求头
使用EventSourcePolyfill插件后 虽然可以自定义请求头 但是EventSourcePolyfill会多次发请求 而且没有请求方式
如何正确的使用EventSourcePolyfill 或者 new EventSource如何添加请求头呢?
new EventSource
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
Nymph_Zhu 2024-08-29 14:20关注// 预检请求的URL const checkUrl = '/events'; // 发送预检请求 fetch(checkUrl, { method: 'OPTIONS', // 使用OPTIONS方法发送预检请求 headers: { 'Authentication': 'Bearer YOUR_TOKEN', // 添加需要的请求头 }, // 其他需要的请求设置 }) .then(response => { // 预检请求成功,可以安全地创建EventSource const eventSource = new EventSource('/events', { headers: { 'Authentication': 'Bearer YOUR_TOKEN', // 添加需要的请求头 }, }); // 处理服务器发送的事件 eventSource.onmessage = function(event) { // 处理事件 console.log(event.data); }; }) .catch(error => { console.error('预检请求失败:', error); });解决 无用评论 打赏 举报