2016-04-27 16 views
0

私にデータを返すPOSTリクエストを作成しようとしています。このデータを自分のルートにプッシュしてインデックスルートに追加する必要があります。私のAPIコールを聞きます:リクエストでエクスプレスルータで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呼び出しを行うためにrequestを使用したいと思います。ただ、結果をCONSOLE.LOGする

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; 

が、私はエラーを取得:私はこのような試みている

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

はので、私は私のparamsで渡している方法で、このですか?このデータをどのように私の '/'経路に送ることができますか?変数に保存して渡すことはできますか?それとももっと良いパターンがありますか?

+0

あなたがここに実現したいのか明確ではありません。あなたは 'post'リクエストを行い、' get'ルートだけを定義します。 'post'リクエストを扱うルートはどこですか? 'resBody'にはどのようなデータがありますか? – jahnestacado

+0

「GET」ルートが定義されていることがわかりました。受信アプリケーションでJSONリクエストを処理できるように、Expressアプリケーションにボディパーサーを追加しても表示されません。 '' body-parser ''を追加しましたか? –

答えて

0

はあなたが指定する必要があなたの要求のbodyとしてparams、そしてあなたも、おそらくJSONにコンテンツタイプを設定する必要があります。

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

これは私には理解できないエラースタックを与えます: yntaxError:Object.parse(ネイティブ)の の予期しないトークン at Request._callback(/Users/Zach/foodopennow/routes/index.js:29:24) ) at Request.self.callback – user3839756

+0

これはおそらく、応答本体で 'JSON.parse'を呼び出そうとしているためです。上記の更新版をお試しください。 – duncanhall

関連する問題