node.js - 如何根据用户表单输入查询api

标签 node.js reactjs express post get

我有一个 Node 应用程序,我在其中调用 google place api 并将该数据发送到前端。在前端,我有一个发布到我的 Node 服务器的基本表单。我想根据用户表单输入从 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) 
}
});
})

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

最佳答案

客户端

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

服务器端

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

关于node.js - 如何根据用户表单输入查询api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349153/

相关文章:

node.js - 解析回调请求时出现多方错误

javascript - 在抛出的对象中传递错误原因/如何处理现代 JavaScript 中的错误

javascript - ReactFire - 将 Firebase 绑定(bind)到 React 状态时获取 'Objects are not valid as a React child'

mysql - Sequelize.js 无法在关联表字段的 WHERE 子句中生成条件

javascript - 无法读取未定义的属性 'totalQty'

node.js - Express JS 反向 URL 路由(Django 风格)

javascript - 如何让 javascript 不能使用 window.* 方法

javascript - Webpack "devtool eval"在 devtools 中没有显示正确的文件内容

javascript - 如何从 URL 中获取参数

node.js - 使用Passport基于动态路由进行认证