如何修复 EventSource 未定义错误?

4

我正在为我的Next JS项目添加SSE事件。 我有一个用于访问SSE事件的URL。

以下是代码:

const ssEvents = new EventSource(stream_url,{withCredentials:false})
  
  ssEvents.addEventListener("participant.details", (e)=>{
    var data = JSON.parse(e.data)
    console.log(data)
  })

我遇到了“EventSource未定义”的错误。由于EventSource是js中的内置库,我甚至可以在其中访问addEventListener。但是在执行时,它显示“EventSource未定义”。我不知道为什么会出现这种情况。我是否漏掉了需要添加到我的代码中的任何内容?请给我一些解决方案来修复它。代码是TypeScript编写的。我需要添加任何其他东西吗?
错误跟踪:
error - pages/index.tsx (55:19) @ Home
ReferenceError: EventSource is not defined

  54 | 
> 55 |   const ssEvents = new EventSource(stream_url,{withCredentials:false})
     |                   ^
  56 | 

tsConfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "src/utils/analytics/index.js",
    "react-google-captcha.d.ts",
    "src/providers/apollo.tsx",
    "src/providers/apollo-client.ts",
    "src/utils/wallet/walletManager.js"
  ],
  "exclude": ["node_modules"]
}

2
它真的说“EventSouce”未定义吗?这可能是某个地方的拼写错误证据。 - Wyck
1
这是服务器端代码吗?如果是,你是否使用了 require("eventsource"); 呢? - Wyck
1
你的 TypeScript 版本至少是 2.7 吗? - Nick McCurdy
1
你能否提供一个链接到 TypeScript playground 并重现这个问题的示例? - Nick McCurdy
1
请提供一个 [mre],可能是因为您正在尝试在应用程序被服务器端呈现时调用 new EventSource(...)。确保您从 useEffect 中调用它。 - juliomalves
显示剩余11条评论
2个回答

2

你的问题在于后端使用了NextJS。

EventSource 在Node上不存在。

请确保你的SSE代码只在浏览器中运行。


1
那你会如何测试呢?Node.js库似乎有一个EventSource - sf8193

0

我也遇到过这样的问题,使用的是 Nuxt3(不是 NextJS)。 我的解决方案是,通过在使用它的文件中添加client标记(在 Nuxt3 中为<ClientOnly>),使该文件仅在客户端渲染。

但我认为在 NextJS 中,你可以在该文件的顶部添加'use client'

参考资料:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接