【问题标题】:How to query api based on user form input如何根据用户表单输入查询api
【发布时间】:2019-10-11 22:27:32
【问题描述】:

我有一个节点应用程序,我在其中调用 google places api 并将该数据发送到前端。在前端,我有一个发布到我的节点服务器的基本表单。我想根据用户表单输入从 api 调用返回数据。

我能够将表单发布到服务器并在请求对象中看到数据,但是我无法弄清楚如何使用这些数据根据表单输入正确查询 api?

形式

 <form method="post" class="form" action="http://localhost:3005/dyno">
<fieldset class="form-fieldset ui-input __first">
  <input type="text" name="interests" id="username" tabindex="0" />
  <label for="intrests">
    <span data-text="Interests">Intrests</span>
  </label>
</fieldset>

<fieldset class="form-fieldset ui-input __second">
  <input type="text" name="location" id="email" tabindex="0" />
  <label for="location">
    <span data-text="Location">Location</span>
  </label>
</fieldset>

  <input type="submit" value="Submit" />
  </form>

记录我需要的数据的服务器端代码

app.post('/dyno', function(request, response){

console.log(request.body.interests)
console.log(request.body.gender)

response.end()

});

API 调用

 _EXTERNAL_URL = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.663918,-73.8820044&radius=2500&type=gyms&keyword=fitness&key=${KEY}`;

app.get('/ruckus',(req, res) => {
request(_EXTERNAL_URL, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) 
res.send(body) 
}
});
})

如何根据用户输入的表单数据,根据半径、类型和关键字参数返回数据?

【问题讨论】:

  • 您只需使用从提交的表单中获得的任何数据形成 _EXTERNAL_URL。类似https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.663918,-73.8820044&amp;radius=${req.body.radius}&amp;type=${req.body.type}&amp;keyword=${req.body.keyword}&amp;key=${KEY};
  • 那不行,请求数据在不同的端点
  • 你不能合并这两个端点?
  • 您将如何访问这些端点?
  • 一个调用外部api,另一个从表单接收post数据,我不明白你如何将两者结合起来。

标签: node.js reactjs express post get


【解决方案1】:

客户端

  • 防止表单提交默认。
  • 使用表单输入形成正文或查询。
  • 向“http://localhost:3005/dyno”发出获取请求
  • 呈现从该请求收到的响应。

服务器端

  • 您创建了一个名为“/dyno”的端点
  • 从请求中获取正文/查询参数
  • 形成 URL 以向 Google Places API 发出请求
  • 发出请求并将响应返回给客户端

【讨论】:

  • 合并它们但是无法通过前端获取调用外部 api 吗?
  • @RomaneGreen 您可以使用前端的 fetch 直接向外部 API 发出请求
  • @RomaneGreen 您可以直接从表单输入控件的值解析 external_URL 中的这些变量。
  • 我使用的 Google Places API 只是服务器端
  • @RomaneGreen 您只想在提交表单时调用 Google Places API 对吧?
猜你喜欢
  • 1970-01-01
  • 2021-03-15
  • 2017-09-24
  • 1970-01-01
  • 2018-07-28
  • 2019-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多