繁体   English   中英

通过请求在快速路由器中进行POST api调用

[英]make a POST api call in express router with request

我正在尝试发出将数据返回给我的POST请求。 然后,我想将此数据推送到我的路由以添加到我的索引路由。 这是我的API调用:

https://api.locu.com/v2/venue/search 

{
  "api_key" : "my API key",
  "fields" : [ "name", "description", "location", "contact", "website_url", "menu_url", "open_hours" ],
  "venue_queries" : [
    {
        "categories" : "restaurant",
        "location" : {
        "geo" : {
          "$in_lat_lng_radius" : [44.0521, -123.116207, 6000]
        }
      },
      "delivery" : {
        "will_deliver" : true
      }

    }
  ]
}

如果我在邮递员中提出此请求,那么我会得到期望的数据。

我想使用请求进行此api调用。 我已经这样尝试过:

var express = require('express');
var router = express.Router();
var request = require('request');

var params = {
  "api_key" : "myApiKey",
  "fields" : [ "name", "description", "location", "contact", "website_url", "menu_url", "open_hours" ],
  "venue_queries" : [
    {
        "categories" : "restaurant",
        "location" : {
        "geo" : {
          "$in_lat_lng_radius" : [44.0521, -123.116207, 6000]
        }
      },
      "delivery" : {
        "will_deliver" : true
      }

    }
  ]
}

request.post({url:'https://api.locu.com/v2/venue/search', params}, function(err,httpResponse,body){
    var resBody = JSON.parse(body)
    console.log(resBody);
})

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

只是为了console.log结果,但我得到了错误:

{ status: 'error',
  http_status: 400,
  error: 'Request body is not a valid JSON object.' }

这是因为我传递参数的方式吗? 如何将这些数据发送到我的“ /”路线? 我可以将其保存到变量然后传递给我吗? 还是有更好的模式呢?

您需要将params指定为请求的body ,并且还可能将内容类型设置为JSON:

request.post({
    url:'https://api.locu.com/v2/venue/search', 
    body:params,
    json: true
}, function(err, response, body){
    console.log(body);
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM