将ID从POST请求传递到单独的端点

时间:2018-12-29 06:54:05

标签: javascript node.js express yelp yelp-fusion-api

我正在自学Node.js,并试图用Yelp的API填充一个页面,其中列出了附近企业的营业时间和营业时间。我在Express中创建了一个到我的页面的POST路由,并使用Yelp Fusion客户端调用了Yelp API。我能够收集一个ID数组,这些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,因为我已经用尽了所有想法。预先感谢您的帮助。

1 个答案:

答案 0 :(得分: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);
}