【问题标题】:make a POST api call in express router with request使用请求在快速路由器中进行 POST api 调用
【发布时间】:2016-04-27 15:50:10
【问题描述】:

我正在尝试发出将数据返回给我的 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
      }

    }
  ]
}

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

我想使用 request 来进行这个 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.' }

这是因为我传递参数的方式吗?如何将此数据发送到我的“/”路线?我可以将它保存到一个变量然后传递它吗?或者有更好的模式吗?

【问题讨论】:

  • 不清楚你想在这里实现什么。你做了一个post 请求,你只定义了一个get 路由。处理post 请求的路由在哪里?您希望resBody 拥有哪些数据?
  • 我只看到定义了一个GET 路由,我看不到您是否已向您的 Express 应用程序添加了一个正文解析器以允许它处理传入的 JSON 请求。你加了"body-parser"吗?

标签: javascript node.js http httprequest


【解决方案1】:

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

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

【讨论】:

  • 这给了我一个我不明白的错误堆栈: yntaxError: Unexpected token o at Object.parse (native) at Request._callback (/Users/Zach/foodopennow/routes/index.js :29:24) 在 Request.self.callback
  • 这可能是由于尝试在响应正文上调用JSON.parse 引起的。试试上面的更新版本。
猜你喜欢
  • 1970-01-01
  • 2018-10-16
  • 2018-04-05
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多