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 did : created a node api for get request and post and created a socket server i tried to consume the app .

"issue:" 1. I tried to consume the api but unable to get the data in socket server and 2. If it worked also how can i get the this socket data on button click in angular application

Note: 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)

Add Comment
1 Answer(s)

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

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.