问题描述
问题:
我正在我的反应应用程序上实现stormglass.io api。我使用 axios 进行 api 调用。当我使用包含在标头中的 api 密钥进行 api 调用时,它工作正常,但是当我尝试将 api 密钥存储在 .env 文件中时(出于安全原因),当我执行api 调用。
预期结果:
我应该得到我的 api 响应数据,但由于某种原因,当它存储在 .env 文件中时,api 密钥不被接受。
yarn run v1.22.5
$ next dev
ready - started server on http://localhost:3000
browserslist: caniuse-lite is outdated. Please run:
npx browserslist@latest --update-db
info - Loaded env from /home/dill5446/git_workspace/pdill.dev/pdill.dev/.env
event - compiled successfully
xhr.js?b50d:177 GET https://api.stormglass.io/v2/weather/point?lat=21.3&lng=-157.8¶ms=secondarySwellDirection,secondarySwellHeight,secondarySwellPeriod,windWaveDirection,windWaveHeight,windWavePeriod,swellDirection,swellHeight,swellPeriod,waveDirection,waveHeight,wavePeriod,windDirection,windSpeed,gust,waterTemperature,currentDirection,currentSpeed,cloudCover,airTemperature 403 (FORBIDDEN)
我尝试过的解决方案:
我尝试添加一个我读过的“dotenv”包作为可能的解决方案。我还添加了一个我读过的“dotenv-webpack”依赖项。我将以下代码添加到我的 next.config.js(为了记录,我在使用配置文件方面不是很有经验):
const webpack = require('webpack')
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
module.exports = {
webpack: (config) => {
config.plugins.push(
new webpack.DefinePlugin({
'process.env.REACT_APP_API_KEY': JSON.stringify(process.env.REACT_APP_API_KEY)
})
)
return config
}
}
const Dotenv = require('dotenv-webpack')
module.exports = {
plugins: [
new Dotenv({
path: './.env',// load this Now instead of the ones in '.env'
safe: true,// load '.env.example' to verify the '.env' variables are all set. Can also be a string to a different file.
allowEmptyValues: true,// allow empty variables (e.g. `FOO=`) (treat it as empty string,rather than missing)
systemvars: true,// load all the predefined 'process.env' variables which will trump anything local per dotenv specs.
silent: true,// hide any errors
defaults: false // load '.env.defaults' as the default values if empty.
})
]
}
api 调用看起来像这样(缩短):
const API_KEY = process.env.REACT_APP_API_KEY
const apiCall = () => {
Axios.all([
Axios.get(`https://api.stormglass.io/v2/weather/point?lat=${lat}&lng=${lng}¶ms=${params}`,{
headers: {
Authorization: `${API_KEY}`
}
}
),Axios.get(`https://api.stormglass.io/v2/tide/extremes/point?lat=${lat}&lng=${lng}&start=${today.toISOString()}&end=${tenDaysOut.toISOString()}`,{
headers: {
Authorization: `${API_KEY}`
}
})
])
.then(async (response) => await setData(response))
.catch((error) => console.error(error))
.finally(() => setLoading(false))
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)