Как использовать сокет в node.js, чтобы ответить клиенту и администратору явно и отдельно, используя HTML-файл? - PullRequest
0 голосов
/ 14 января 2019

Я написал API для клиентской стороны в узле, и я хочу, чтобы при достижении клиентом конечной точки клиенту показывался только строковый ответ, но при переходе клиента к API-файлу HTML-файл должен обновляться на стороне клиента. Пожалуйста, дайте мне знать, как генерировать отдельные ответы для клиента и администратора из одного API в узле.

app.get('/', function(req, res) {
   res.sendfile('index.html');//sending file in response to client
});
// something like above  is been done which sends response file to the client but i wants that it only updated and shown to the admin at the time of request.

const app = express();
const port = process.env.PORT || 3000;
const server = require('http').createServer(app);
         //socket imported
const io = require('socket.io')(server);
       //end-point 'ring'
app.post('/ring', (request, response)=> 
{
    console.log(request.body); 
    const data=request.body;

    if(!data)
    {
        //if data is not sent then error status
        return  response.status(400).send('bad request');
    }
    // here i need to implement explicit responses
        console.log((`data is----> ${data}`));
    //here i'm emitting my json object to the html file
    // this json object should be sent to the html to show
    io.emit('message'{'requestbody':request.body,'status':'ringing'});
    // sending success response to the client
    response.status(200).send('ringing');
});

Index.html code

<body>
    <script src=”/socket.io/socket.io.js”></script>

    <script 
    //initializing socket
        var socket = io();
    //trying to recieve json object from socket
        socket.on(‘message’, addMessages)>//calling the addMessage function
    </script>

    <script>
        function addMessages(message)
        {
        //setting the text extracted from json object
           $(“#messages”).append(`
        //setting probeId  
              <h4> ${message.probeId} </h4>
        //setting status
              <p>  ${message.status} </p>`)
        }
    </script>

  //my 'index.html' file should be updated when user hits the ring api and user gets a string response.

1 Ответ

0 голосов
/ 14 января 2019

Я почти уверен, что вам не нужен сокет для того, что вам нужно. Если мое понимание вопроса достаточно хорошее, вы можете просто добавить параметр, чтобы отделить тип возвращаемого значения

app.post('/ring', (request, response)=> 
        {
            console.log(request.body); 
            const data=request.body;

            if(!data)
            {
                //if data is not sent then error status
              return  response.status(400).send('bad request');
            }
            if(data.returnType === 'html'){
                response.sendFile(path.join(__dirname + '/index.html'));
            } else {
                response.status(200).send('ringing');
            }
})

returnType - это параметр POST для разделения типов возврата.

обновление:

если вы хотите обновить свой индекс

app.post('/ring', (request, response)=> 
        {
            console.log(request.body); 
            const data=request.body;

            if(!data)
            {
                //if data is not sent then error status
              return  response.status(400).send('bad request');
            }
            if(data.returnType === 'html'){
                response.sendFile(path.join(__dirname + '/index.html'));
            } if(data.returnType === 'json'){
              // Business logic here
              let result = { a: 'aez' };
              return response.json(result);
            } else {
                response.status(200).send('ringing');
            }
})

А в вашем html

<body>
   <script>
       $("#envoyer").click(function(){
        $.ajax({
                 url : 'send_mail.php',
                 type : 'POST',
                 data : 'dataType=json'
                 success: handle
               });

     });

     function handle(result, status)
      {
        //setting the text extracted from json object
        $(“#result”).append(`<div> ${result.a} </div>`)
      }
     </script>
</body>
...