我可以在node.js中调用单个端点中的多个路由器端点吗

5sxhfpxr  于 2023-06-22  发布在  Node.js
关注(0)|答案(2)|浏览(156)

我创建了一个GET端点调用router.get('/alarm1',authenticateUser, getSiteIds, async (req, res) => {//body})。我已经创建了多个路由器,如上面的一个alarm2,alarm3和alarm4。然后,我需要调用每个端点,并在调用所有报警端点router.get('/all-alarms',authenticateUser, getSiteIds, async (req, res) => {//body})路由器调用后返回每个路由器调用的响应。但我找不到办法。我发现了一种使用node.js中的进程来实现这一点的方法。
all-alarms.js文件

const { spawn } = require('child_process');
const express = require('express');
const { getSiteIds } = require('../../middleware/sites/getSiteIds');
const { authenticateUser } = require('../../middleware/auth/authenticateUser');
const app = express();
const router = express.Router();
const path = require('path');

// Create the combined endpoint
router.get('/', authenticateUser, getSiteIds, async (req, res) => {
  const endpoints = [
    '/alarm1',
    '/alarm2',
    '/alarm3',
    '/alarm4'
    ];
  const bearerToken = req.headers.authorization; // Retrieve the bearer token from the initial request
  // Create an array to store the child processes
  const processes = [];

  // Function to handle each endpoint
  const handleEndpoint = (endpoint) => {
    return new Promise((resolve, reject) => {
      const process = spawn('node', [path.join(__dirname, '../../', 'call-alarms.js'), endpoint,bearerToken]);

      process.stdout.on('data', (data) => {
        resolve(JSON.parse(data));
      });

      process.stderr.on('data', (data) => {
        reject(data.toString());
      });

      process.on('exit', (code) => {
        console.log(`Child process exited with code ${code}`);
      });
    });
  };

  // Call each endpoint in parallel using child processes
  try {
    for (const endpoint of endpoints) {
      const process = handleEndpoint(endpoint);
      processes.push(process);
    }

    const results = await Promise.all(processes);

    // Combine the results into a single response
    const aggregatedData = {
      'alarm1': results[0],
      'alarm2': results[1],
      'alarm3': results[2],
      'alarm4': results[3]
    };

    res.json(aggregatedData);
  } catch (error) {
    res.status(500).json({ error: 'Error occurred while aggregating data.' });
  }
  //  finally {
  //   // Kill all child processes
  //   processes.forEach((process) => {
  //     // process.kill();
  //   });
  // }
});

module.exports = router;

call-alarms.js文件

const axios = require('axios');

// Get the endpoint URL from the command line arguments
const endpoint = process.argv[2];

// Get the bearer token from the command line arguments
const bearerToken = process.argv[3];

// Make the HTTP request to the specified endpoint with the bearer token
axios.get(`http://localhost:3000${endpoint}`, {
  headers: {
    Authorization: bearerToken // Set the bearer token as the authorization header
  }
})
  .then((response) => {
    // Send the response back to the parent process
    process.stdout.write(JSON.stringify(response.data));
    process.exit(0);
  })
  .catch((error) => {
    // Send the error message back to the parent process
    process.stderr.write(error.message);
    process.exit(1);
  });

但是,这里我面临的问题是,我不需要为这些已经创建的路由器调用包括一个http调用,作为axios.get( http://localhost:3000 ${endpoint}`。我如何使用路由器调用而不是axios http调用来实现这一点?如果我能做到这一点,没有过程就更好了。

u4dcyp6a

u4dcyp6a1#

您应该将后端逻辑和端点分开,以便能够在不同的端点中重用代码的某些部分。

const express = require('express');

const app = express();
const router = express.Router();

function alarm1 () {
  return {
    "result": 'alarm1'
  };
}

function alarm2 () {
  return {
    "result": 'alarm2'
  };
}

// some middlewares
router.use(authenticateUser);
router.use(getSiteIds);

// the routes
router.get('/all-alarms', (req, res) => {
  res.json({
    "alarm1": alarm1(),
    "alarm2": alarm2()
  });
});
router.get('/alarm1', (req, res) => {
  res.json(alarm1());
});

router.get('/alarm2', (req, res) => {
  res.json(alarm2());
});
vltsax25

vltsax252#

这是在单个端点中创建多个路由的简单方法

// this is the routes.js file

const express = require('express');
const router = express.Router();

router.get('/', Router 1)

// router2 

router.get('/', 'Router 2' ) 

module.exports = router;

// this is app.js file

const express = require('express');
const app = express();

const router1 = require('./router1');
const router2 = require('./router2');

app.use('/endpoint', router1);
app.use('/endpoint', router2);

相关问题