Shyam Nair
Shyam Nair

Reputation: 159

How to call node api response in socket.io server

Scenario: Creating a Node API (GET) calling that API in socket.io Node server and calling this socket server in angular client.

What i have done: Created a node API for get request and post and created a socket server I tried to consume the app.

Issues: 1. I tried to consume the API but was unable to get the data in the socket server and 2. If it works, also how can i get the socket data on button click in angular application?

Note: I'm running Node API on 3000 server and running socket server on 3001.

Below is my code

Node api code runnning on 3000 port:

const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express()
const port = 3000

let books = [{
    "isbn": "9781593275846",
    "title": "Eloquent JavaScript, Second Edition",
    "author": "Marijn Haverbeke",
    "publish_date": "2014-12-14",
    "publisher": "No Starch Press",
    "numOfPages": 472,
}];

app.use(cors());

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/book', (req, res) => {
    const book = req.body;

    // output the book to the console for debugging
    console.log(book);
    books.push(book);

    res.send('Book is added to the database');
});

app.get('/book', (req, res) => {
    res.json(books);
});



app.listen(port, () => console.log(`Hello world app listening on port ${port}!`));

Socket .io server running on 3001

  var app = require('express')();
    var http = require('http').createServer(app);
    var io = require('socket.io')(http);
    
    const apiUrl="http://localhost:3000/book"
    
    
    io.on('connection', function (socket) {
        socket.on('getBanners', function(data){
          request.get(apiUrl,function (error, response, body){
              console.log(body)
            socket.emit('result', {res:JSON.parse(body)})
          })
        });
      });
    
    http.listen(3001, function(){
        console.log('listening on *:3001');
    });

Note: Node API server --> socketio server (not client)

Upvotes: 3

Views: 3417

Answers (2)

amritashan
amritashan

Reputation: 583

I wouldn't recommend going by that design you have.

Unless there is a very specific/important reason to have the socket.io server on a different port than the HTTP server, I would recommend having your socket.io server upgraded from the HTTP server itself.

eg.

In bin/www:

const { initSocketIOServer } = require('../socket-server');

const port = normalizePort(process.env.PORT || '3001');
app.set('port', port);

/**
 * Create HTTP server.
 */

const server = http.createServer(app);
initSocketIOServer(server);

In socket.server.js

module.exports.initSocketServer = (server) => {
  io = require('socket.io')(server);

  io.on('connection', (socket) => {
    console.log('client connected');

    socket.on('getBanners', (event) => {
      // handle getBanners event here
    });
  });
};

However, going by your example, if you really need to make a request to the HTTP server to fetch data, you might want to use the HTTP library:

socket.on('getBanners', (event) => {
  http.get({
    hostname: 'localhost',
    port: 3000,
    path: '/book',
    agent: false  // Create a new agent just for this one request
  }, (res) => {
    // Do stuff with response, eg.
    const socketResponse = processBooks(book);
    socket.emit('result', socketResponse);
  });
});

Upvotes: 3

Govi-Boy
Govi-Boy

Reputation: 99

You can use any node package for requests like request https://github.com/request/request here

Upvotes: 0

Related Questions