伙计们,我在这里遇到了来自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上的更改.