Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
How to send response using twice or more callback in one request

I'm using express and the request POST look like that

router.post('/', function(req, res, next){
 var data = req.body;
 getRandom(data, function(value){
     res.json({value: value});
 });
});

POST is sent through ajax and then update textarea with new data.

 $.ajax({
           type: "POST",
           url: "/",
           data: JSON.stringify(datareq),
           dataType: 'json',
           contentType: 'application/json',
           success: function(x){
               $.each(x, function(index, value) {
                  $('.textarea').append(value + '\n');
               });
           },
           error: function(x) {
                console.log(x + 'error');
          }
       });

How to send this using one POST and a few response. User received one data in textarea when cb finished and then another data and so one till the end.

<textarea>
 data 1 - 1sec
 data 2 - 2sec leater
 data 3 - 3 second later
 ...
</textarea>

I add Time (1sec ...) only to show that callback has a lot to do to send another response.

Of course this not working because res.send() close connection and I received error

So how to achieve my idea, to sending simultaneously after post request. I want to give user data very fast, then another one when is ready not waiting for all and then send response.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can't


Reason:

Http closes connection after sending response. You can not keep it open and sending multiple responses to the client. HTTP doesn't support it.

Solution 1:

Simply put a timer at client side and request periodically.

Solution 2 (Recommended):

Use socket, and pass data through it. socket.io is the socket library for nodejs applications. It is very easy to use. Set up a connection, keep sending data from server and receive it on client side.


Just to add on the answer. This answer explains why res.send closes the connection.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda