将POST请求中的ID传递给单独的端点

问题描述 投票:1回答:1

我正在教自己Nodejs,并且我正在尝试使用Yelp的API填充附近企业开始和结束时间列表的页面。我在Express中创建了一个到我页面的POST路由,使用Yelp Fusion客户端调用Yelp API。我能够收集一个必须在另一个端点使用的ID数组,以便获取操作时间,但是,尽管在请求中设置了限制,但仍然会在执行此操作时收到TOO_MANY_REQUESTS_PER_SECOND错误。

Server.js

var express = require("express");
var app = express();
var yelp = require("yelp-fusion");
var bodyParser = require("body-parser");

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
let client = yelp.client("API_HIDDEN");

app.get("/", function(req,res){
    res.render("landing");
});

///Initial request made to obtain business ids
app.post("/", function(req, res){
    client.search({
        term: 'cafe',
        location: 'Oakland',
        limit: 20
    }).then(response => {
        var ids = [];
        var businesses = response.jsonBody.businesses;
        var idName = businesses.map(el => {
            ids.push(el.id);
        });

        // request separate endpoint, passing ids from the ```ids```array
        for(var x = 0; x < businesses.length; x++){
            client.business(ids[x]).then(response => {
                console.log(response.jsonBody.hours);
            })}.

        res.render("search");
    }).catch(e => {
        console.log(e);
    });
})

app.listen(3000);

我试过在for循环内外调用client.businesses[id],但这也导致了错误。我对此行为感到困惑,因为我只进行了20次调用,远远低于最小值,但如果不是数组,也可能如何传递id,因为我的想法已经用完了。预先感谢您的帮助。

javascript node.js express yelp yelp-fusion-api
1个回答
2
投票

随着时间的推移传播api电话。

var delay = 1.1 * 1000; // 1.1 seconds in milliseconds  
for(var x = 0; x < businesses.length; x++){
  setTimeout(function(i){
      client.business(ids[i]).then(response => {
      console.log(response.jsonBody.hours);
      });  
  },delay*x,x);
}
© www.soinside.com 2019 - 2024. All rights reserved.