Node.js 的多个 API 请求

用户414977

我试图在 for 循环中调用多个外部 api,但根据结果,我只从 for 循环中获得一次迭代,将响应发送回。

是的,这不是处理多 api 请求的正确方法,请建议最好的方法,因为它必须是顺序 req/res

第一个请求 - 调用以查找相应的 api。Response 保存要输入到两个在 for 循环中调用的 api 的数据。

For-loop Second API Request - 将数据提供给第三个 API 请求。

var express = require('express');
var bodyParser = require('body-parser');
var Request = require("request");

var app = express();
app.use(bodyParser.json());

app.post('/building/', function (req, res) {
	'use strict';

	var myObject = null;

	var callSiteApi = {
		uri: 'http://localhost:8080/site/',
		body: JSON.stringify(req.body),
		method: 'POST',
		headers: {
			'Content-Type': 'application/json'
		}
	}
	// First External API Call
	Request(callSiteApi, function (error, response) {
		if (error) {
			console.log('ERROR with user request.');
			return response.sendStatus(500); // Return back that an error occurred
		} else {
			// Get data from response.body

    
			var materialquerystring = "mat="+response.body.material+"&date="+response.body.date;
            var floor = response.body.floor;

			for (var i = 0; i < floor.length; i++) {

				matereialValueURL = "http://localhost:8080/material/q="+materialquerystring;
				// Second External API Call within for loop
				Request.get(materialValueURL, (error, response, body) => {
					if (error) {
						console.log(req.error);
						
					}
					materialObject = JSON.parse(body);
          var valuequerystring = "value="+materialObject.value;
          // do somehting with materialObject
          
					console.log("first request iteration =" + i);

					sitevalueURL = "http://localhost:8080/value/q="+valuequerystring;
					// Third External API Call within for loop
					Request.get(sitevalueURL, (error, response, body) => {
						if (error) {
							logger.debug('[' + pid + '] ' + req.error);
							//return console.dir(error);
						}
						valueObject = JSON.parse(body);           
            console.log("second request iteration =" + i);
            // do somehting with valueObject 7 materialObject
            var a = materialObject.a;
            var b = valueObject.b;
            var c = a+b;
            
						
					});
				});
			}

			res.writeHead(200, {
				'Content-Type': 'application/json'
			});
			res.end('{"value-1":"a","value-2":"b","value-3":"c","material":"materialquerystring","value":"valuequerystring"}');
		}
	});
});

本尼·鲍尔斯

如果您只需要从用户的请求中获取一个数字,然后多次发出相同的 http 请求,则应该这样做。我带来了一个pointfreemap助手从直列四缸,使事情变得更容易一些。

您可能需要在这里和那里进行一些调整,特别是在最后then条款中

const map = require('crocks/pointfree/map');

const app = express();

app.use(bodyParser.json());

const range = integer => [...new Array(integer).keys()]
const replicate = (i, x) => range(i).fill(x)

const handleError = error => {
  logger.debug(`['${pid}'] ${error.reponse.error}`)
  return error;
}

const getMaterialURIs = response =>
  replicate(response.body.floor.length, `http://localhost:8080/material/q=${response.body.material}`)

const processMaterialResponse = response => {
  doSomethingWithMaterial(response.body)
  return response;
}

const getSiteValueURI = response =>
  `http://localhost:8080/value/q=${response.body.value}`;

const processSiteValueResponse = response => {
  doSomethingWithSiteValue(response.body)
  return response;
}

app.post('/building/', function (req, res) {
  const uri = 'http://localhost:8080/site/';
  const body = JSON.stringify(req.body);
  const method = 'POST';
  const headers = { 'Content-Type': 'application/json' };

  // First External API Call
  Request({uri, body, method, headers})
    // 1: fetch to derive the material URI
    .then(getMaterialURIs)
    // 2: fetch from that material URI
    .then(map(Request.get))
    .then(Promise.all)
    // 3: process the material response
    .then(map(processMaterialResponse))
    // 4: derive the siteValueURI 
    .then(map(getSiteValueURI))
    // 5: fetch the siteValueURI
    .then(map(Request.get))
    .then(Promise.all)
    // 6: process the site value response
    .then(map(processSiteValueResponse))
    .catch(handleError)
    .then(response => {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end('{"material":"materialquerystring","value":"valuequerystring"}');
    });
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章