簡體   English   中英

如何在 socket.io 服務器中調用節點 api 響應

[英]How to call node api response in socket.io server

場景:在 socket.io 節點服務器中創建一個節點 API (GET) 調用該 API 並在 ZD12DB8624A0FFC5B78 客戶端中調用此套接字服務器。

我做了什么:為獲取請求和發布創建了一個節點 API 並創建了一個套接字服務器,我嘗試使用該應用程序。

問題: 1. 我嘗試使用 API 但無法獲取套接字服務器中的數據 2. 如果它有效,我如何在 angular 應用程序中單擊按鈕時獲取套接字數據?

注意:我在 3000 服務器上運行節點 API 並在 3001 上運行套接字服務器。

下面是我的代碼

在 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 服務器運行在 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');
    });

注意:節點 API 服務器 --> socketio 服務器(不是客戶端)

我不建議您采用那種設計。

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.

例如。

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

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

但是,以您的示例為例,如果您確實需要向 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);
  });
});

您可以在此處使用任何節點 package 請求請求https://github.com/request/request

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM