我有一个 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/