warisFairy 2024-08-29 13:45 采纳率: 44.4%
浏览 9

new EventSource

new EventSource 不可以设置请求头
使用EventSourcePolyfill插件后 虽然可以自定义请求头 但是EventSourcePolyfill会多次发请求 而且没有请求方式
如何正确的使用EventSourcePolyfill 或者 new EventSource如何添加请求头呢?

  • 写回答

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);
    });
    
    评论

报告相同问题?

问题事件

  • 创建了问题 8月29日