首页 > 解决方案 > 导出服务器端功能供客户端使用

问题描述

我有一个尝试使用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 代码可以访问,这样我就可以geocoderkeydown表单<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)
    })

});

标签: javascriptjquerynode.jsmapbox

解决方案


您不能在客户端公开您的后端。另外,你不应该。

您需要在两端之间进行通信并假设它们不相关。

向服务器发送请求并处理返回的响应。

$(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.

推荐阅读