简体   繁体   English

如何在 socket.io 服务器中调用节点 api 响应

[英]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.场景:在 socket.io 节点服务器中创建一个节点 API (GET) 调用该 API 并在 ZD12DB8624A0FFC5B78 客户端中调用此套接字服务器。

What i have done: Created a node API for get request and post and created a socket server I tried to consume the app.我做了什么:为获取请求和发布创建了一个节点 API 并创建了一个套接字服务器,我尝试使用该应用程序。

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?问题: 1. 我尝试使用 API 但无法获取套接字服务器中的数据 2. 如果它有效,我如何在 angular 应用程序中单击按钮时获取套接字数据?

Note: I'm running Node API on 3000 server and running socket server on 3001.注意:我在 3000 服务器上运行节点 API 并在 3001 上运行套接字服务器。

Below is my code下面是我的代码

Node api code runnning on 3000 port:在 3000 端口上运行的节点 api 代码:

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 Socket.io 服务器运行在 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)注意:节点 API 服务器 --> socketio 服务器(不是客户端)

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. 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 :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.jssocket.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:但是,以您的示例为例,如果您确实需要向 HTTP 服务器发出请求以获取数据,则可能需要使用 HTTP 库:

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);
  });
});

You can use any node package for requests like request https://github.com/request/requesthere您可以在此处使用任何节点 package 请求请求https://github.com/request/request

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM