【发布时间】:2020-02-11 15:21:46
【问题描述】:
我有一个带有 React 元素的 HTML 项目(在 html 中传递反应脚本标签),我需要使用谷歌地图 url 保护脚本中的 api 密钥。我是新手,我不确定这是否可能?
我试过'dotenv' 和'dotenv webpack'。
结果:我可以访问我在 .env 中定义的 API-KEY,但只能在终端中通过运行 $ node -r dotenv/config ./src/index.js
// ./src/index.js
console.log(process.env.API_KEY)
我尝试将它存储在一个变量中,并将一个新的脚本标签插入到 HTML 中,如下所示:
// ./src/index.js
require('dotenv-webpack');
var newScript = document.createElement("script");
newScript.src = `https://maps.googleapis.com/maps/api/js?key=${process.env.S3_API}&libraries=places`;
newScript.type = "text/javascript";
target.appendChild(newScript);
我收到Uncaught ReferenceError: require is not defined at index.js
我也试过HtmlWebpackPlugin:
// ./webpack.config.js
const Dotenv = require('dotenv-webpack');
const path = require('path');
module.exports = {
plugins: [
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true
}), // load .env.example (defaults to "false" which does not use dotenv-safe))
new HtmlWebpackPlugin({
template: './web/web.html',
title: 'Custom template using html-loader',
environment: {
'GOOGLE_PLACES_API': process.env.GOOGLE_PLACES_API;
})
]
};
<!-- ./web/web.html -->
...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<%= htmlWebpackPlugin.options.environment %>&libraries=places"></script>
...
不胜感激任何帮助或建议
【问题讨论】:
-
从根本上说,如果您想从浏览器发出 API 请求,那么 API 密钥必须以某种方式在浏览器中可见,这意味着您的服务器需要将其发送到浏览器,这意味着您根据定义公开公开您的 API 密钥。没有办法“保护”它。 — 有一些 Google API 旨在以这种方式使用,而 API 密钥并非旨在“安全”。可能有其他 API 是您一开始不应该仅使用私钥从浏览器访问的。