javascript - 导出服务器端功能供客户端使用
问题描述
我有一个尝试使用MapBox自动完成html
输入字段的功能。我想在 上进行地理编码调用keydown
,这样用户就不必完全输入他们的城市名称。
在app.js
我使用dotenv时,我的 API 密钥可以通过访问process.env.MAPBOX_TOKEN
,并且需要Mapbox
:
应用程序.js:
require('dotenv').config()
const mbxGeocoding = require('@mapbox/mapbox-sdk/services/geocoding');
const geocodingClient = mbxGeocoding({ accessToken: process.env.MAPBOX_TOKEN });
我现在想让geocodingClient
一些客户端 jQuery 代码可以访问,这样我就可以geocoder
在keydown
表单<input>
字段中调用函数。我怎样才能做到这一点?
下面抛出错误geocodingClient is not defined
。如何使此服务器端功能可用于客户端代码?
公共/js/mapBox.js:
$(document).ready(function () {
$('#citySearch').on('keyup', function(){
var location = $(this).val();
console.log("Location: " + location);
async function geocoder(location){
try {
let response = await geocodingClient
.forwardGeocode({
query: location,
limit: 2
})
.send();
console.log(response.body.features[0].place_name)
} catch(err){
console.log(err.message);
}
}
geocoder(location)
})
});
解决方案
您不能在客户端公开您的后端。另外,你不应该。
您需要在两端之间进行通信并假设它们不相关。
向服务器发送请求并处理返回的响应。
$(document).ready(function () {
$('#citySearch').on('keyup', function(){
var location = $(this).val();
console.log("Location: " + location)
//1. request to back end with data and deal with response with
// http libs (ajax, node http/https, axios, etc...)
})
});
// 2. Reach a route to invoke the async function and respond the result
// 3. this should be at the backend and responding an answer to route that respondes to front.
async function geocoder(location){
try {
let response = await geocodingClient
.forwardGeocode({
query: location,
limit: 2
})
.send();
console.log(response.body.features[0].place_name)
} catch(err){
console.log(err.message);
}
}
// this should be at the backend and responding an answer to route that respondes to front.
推荐阅读
- elasticsearch - Elasticsearch query_string 过滤器在非空字符串时使用字段
- python - 如何计算组中的记录数并将它们保存在 csv 文件中?
- python - Fabric3 连接到没有密码的服务器
- ansible - 未安装作曲家 - ansible
- git - 搞砸了我的 git repo,不知道如何正确同步
- java - 如何进行这些类型的字符串模式匹配
- c# - 我可以在用户之间发送数据库吗?
- javascript - HTML:防止在某些标点符号前面有空格之前换行
- python-3.x - PyQt5 ImportError:DLL 加载失败
- ruby-on-rails - 找不到 Api::UsersController 的操作“更新”: