【发布时间】: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