伙计们,我在这里遇到了来自Node的SSE(服务器发送的事件)问题. 我正在制作一个从API接收响应并将其传递给用户的网站,我设法接收到我在客户端(Test0、Test1和测试-未定义/未定义)做出的第一个响应,但当我从客户端发出请求时,其中类型为1或2的请求,这些情况下的测试不会出现在客户端. 我怎么才能解决这个问题??我开始研究上交所,我到了这里,但现在我不能再继续下go 了.

代码是这样的:

app.get('/ask', async (req, res) => {
  const question = req.query.question;
  const type = req.query.type;
  
  res.writeHead(200, {
    'Content-Type':'text/event-stream',
    'Cache-Control': 'no=cache',
    'Connection':'keep-alive'
  })
  
  //msg inicial para estabelecer a conexão
  res.write('\n');

  res.write(`data: teste0\n\n`);
  res.flushHeaders();

    res.write(`data: Teste1\n\n`);
    res.flushHeaders();

  try {
    console.log("entrou no /ask");

    if(type==undefined && question==undefined)
    {
      res.write(`data: teste-undefined/undefined\n\n`);
      res.flushHeaders();
      return;
    }

if(type=="type1")
    {
      const data = await executeQuery(type,question);
   
      res.write(`data: Teste2\n\n`);
      res.flushHeaders();
    }

    if(type=="type2")
    {
      console.log('teste3');
      res.write(`data: teste3\n\n`);
      res.flushHeaders();
    }
   
  } 
  catch (error) {
    console.error('Erro ao interagir com a API', error);
    res.status(500).end('Erro ao interagir com a API');
    console.log(type);
  }
});

在客户端,我这样称呼上交所:

<script>
    const eventSource = new EventSource('/ask');
    const resposta_api = document.getElementById('answer');

    eventSource.onmessage = (event) => {
      const newElement = document.createElement('p');
      newElement.textContent = `message: ${event.data}`;

      // Atualizar o HTML com a resposta parcial recebida
      resposta_api.appendChild(newElement);
    };
  </script>

我的按钮触发器是这个函数:

<script>
    function askQuestion() {
      const question = document.getElementById('question').value;
      const questionType = document.getElementById('questionType').value;

      let url = `/ask?question=${encodeURIComponent(question)}&type=${encodeURIComponent(questionType)}`;

      // Envia a pergunta para o servidor
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.send();
    }
  </script>

当从我的按钮调用/询问时,不会对HTML进行任何更改. 我在浏览器和终端上没有收到任何错误. 我可以看到我的控制台日志(log)‘teste3’,但我在浏览器上看不到我的HTML上的更改.

推荐答案

我认为问题在于,您正试图以两种方式使用/ask/,既作为SSE端点,也作为接受问题的地方.

一旦设置SSE套接字,它就是专用的单向连接,数据只能从服务器流向客户端.客户端无法写入套接字,服务器也无法从中读取.

在您的代码中,我认为您试图将SSE用作一次性连接:客户端提出问题,服务器发回答案,套接字关闭?使用普通的AJAX查询通常更简单.

但是如果你想使用SSE,例如因为await executeQuery()可能非常慢,而且你担心超时,那么你需要做的改变是不是全局创建你的EventSource对象,而是在askQuestion()中创建它. for each 问题重新创建对象.

Node.js相关问答推荐

链接Inbox类方法,范围在哪里以及为什么发生变化?

(0,core_1.default)不是使用@middy/core的lambda处理程序上的函数

如何在Reaction应用程序中查看存储的斑点图像?

无法从MongoDB文档中保存的对象数组中获取对象的属性

如何使用多个参数完成

如何创建具有不同对象类型的数组类型

Rest-Api动态图像路径和Express除非

为什么 docker 容器内的应用程序无法访问它自己的 API 端点?

Prisma 和 Nextjs:重新部署之前内容不会更新

eSignature API 的 NodeJS SDK 是否支持数据流?

kubernetes 上的 nextjs 无法启动

无服务器部署使用无服务器组合抛出`spawn serverless ENOENT`

JavaScript & Node - 将图像文件保存到服务器但无法查看

为什么 req.params.id 返回 undefined未定义?

Node.js、Cygwin 和 Socket.io 走进一家wine 吧……Node.js 抛出 ENOBUFS,所有人都死了

从 Node.js 应用程序查询 Heroku 托管的 Postgres 数据库时出现自签名证书错误

NODEJS 进程信息

PhoneGap/Cordova Android 开发

Javascript在try块内设置const变量

当我try 向我的 S3 存储桶 (Node.js) 发送内容时,AWS 缺少凭证