You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用index.html中Google Places API密钥隐藏与环境变量访问方法

MERN栈支付页面Google Places API密钥处理方案

一、在React项目public/index.html中访问环境变量

React项目中,public目录下的HTML文件可通过特定格式读取环境变量,操作步骤如下:

  1. 在项目根目录创建.env文件,添加带REACT_APP_前缀的变量(React仅识别该前缀的环境变量):
    REACT_APP_GOOGLE_MAPS_API_KEY=你的Google Places API密钥
    
  2. 在public/index.html的Google Maps脚本中,用%变量名%格式替换硬编码的密钥:
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "%REACT_APP_GOOGLE_MAPS_API_KEY%",
        v: "weekly",
        // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
        // Add other bootstrap parameters as needed, using camel case.
      });
    </script>
    
  3. 将.env文件加入.gitignore,防止密钥被提交到版本控制系统。

二、隐藏Google Places API密钥的进阶方案

上述方法仅避免了硬编码密钥,但浏览器加载脚本后仍能解析出密钥。更安全的方式是通过Node.js后端代理请求:

  1. 在MERN栈的后端项目根目录创建.env文件,添加密钥:
    GOOGLE_MAPS_API_KEY=你的Google Places API密钥
    
  2. 后端创建代理接口,比如/api/places/autocomplete,在接口内部调用Google Places API并带上密钥:
    // 示例:使用Express和axios实现代理
    const express = require('express');
    const axios = require('axios');
    const router = express.Router();
    
    router.get('/autocomplete', async (req, res) => {
      const input = req.query.input;
      const apiKey = process.env.GOOGLE_MAPS_API_KEY;
      try {
        const response = await axios.get(`https://maps.googleapis.com/maps/api/place/autocomplete/json`, {
          params: {
            input,
            key: apiKey,
            // 可添加其他参数如types、location等
          }
        });
        res.json(response.data);
      } catch (error) {
        res.status(500).json({ error: '请求Google Places API失败' });
      }
    });
    
    module.exports = router;
    
  3. 前端不再直接加载Google Maps脚本,而是调用后端代理接口获取地址自动补全数据,实现UI上的自动补全功能。

内容的提问来源于stack exchange,提问作者KingJoeffrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:17:57