如何使用 Mapbox GL JS 和 Laravel 后端在 React.js 中渲染 Mapbox 地图而不暴露 API 密钥?

问题描述 投票:0回答:1

我正在开发一个 React.js 项目,我需要渲染 Mapbox 地图。我在 Mapbox Studio 中创建了自定义地图样式,并希望在我的应用程序中使用它。为了避免在客户端暴露我的 Mapbox API 密钥,我使用 Laravel Sanctum 设置了一个 Laravel 后端来处理 Mapbox API 请求。

这是我到目前为止所做的:

在 Laravel 中,我创建了一个 MapboxController.php,它使用 Mapbox Styles API 和我的密钥检索样式。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class MapboxController extends Controller
{
    public function getMapStyle()
    {

        $response = Http::get('https://api.mapbox.com/styles/v1/{username}/{style_id}?access_token='.env('MAPBOX_API_KEY'));


        return response()->json($response->json());
    }
}

Laravel API 将响应返回到我的 React 应用程序,该应用程序应该像这样初始化地图:

import React, { useEffect, useRef } from "react";
import mapboxgl from "mapbox-gl";
import "./Map.css";

const Map = () => {
  const mapContainer = useRef(null);

  useEffect(() => {
    fetch("MY_BACKEND_URL")
      .then((response) => response.json())
      .then((data) => {
        console.log(data); //Logging the response for debugging, the data arrives as expected

        // Initializing the map with the data
        const map = new mapboxgl.Map({
          container: mapContainer.current,
          style: data.style,
          center: [9.984395, 51.145088],
          zoom: 8,
          attributionControl: false,
          logoPosition: "bottom-left",
        });

        const attribution = new mapboxgl.AttributionControl({});
        map.dragRotate.disable();
        map.touchZoomRotate.disableRotation();
        map.addControl(attribution, "bottom-right");

        return () => map.remove();
      })
      .catch((error) => {
        console.error("Fehler beim Laden der Karte: ", error);
      });
  }, []);

  return <div ref={mapContainer} style={{ height: "100vh" }} />;
};

export default Map;

但是,我遇到了一个问题,Mapbox 仍然需要客户端的 API 密钥。这是我在控制台中收到的错误消息:

Map.js:32 Fehler beim Laden der Karte:  Error: An API access token is required to use Mapbox GL. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes
    at e.cS._makeAPIURL (mapbox.js:221:23)
    at e.cS.normalizeStyleURL (mapbox.js:80:21)
    at kr.loadURL (style.js:390:40)
    at Map._updateStyle (map.js:2019:28)
    at Map.setStyle (map.js:1994:25)
    at new Map (map.js:658:18)
    at Map.js:15:21

我正在寻找一种在 React 中渲染地图的方法,而无需在前端提供 API 密钥。在这种情况下,有没有一种方法可以安全地使用 Mapbox,其中 API 密钥保持隐藏,并且仅将必要的数据发送到前端?

reactjs laravel mapbox mapbox-gl-js laravel-sanctum
1个回答
0
投票

你不能,但没关系。如果 向您的 API 密钥添加 URL 限制

,您会做什么
© www.soinside.com 2019 - 2024. All rights reserved.