簡體   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