我正在處理一個專案,我使用 Amazon Cognito 服務進行身份驗證。現在,我有一個檔案,我在其中定義了用戶池,對于那些用戶池配置,我使用了環境變數(帶有前綴 REACT_APP_)但是當我將此包含用戶池的檔案匯入另一個檔案時,它給了我一個錯誤,它不能獲取那些 Env 變數。我提供了下面的代碼以便更好地理解。
用戶池.js
import { CognitoUserPool } from 'amazon-cognito-identity-js'
// This line below is Printing the Env Variable Correctly
// console.log(process.env.REACT_APP_USERPOOL_ID_USER)
const poolData_user = {
UserPoolId: process.env.REACT_APP_USERPOOL_ID_USER,
ClientId: process.env.REACT_APP_CLIENT_ID_USER
}
const poolData_admin = {
UserPoolId: process.env.REACT_APP_USERPOOL_ID_ADMIN,
ClientId: process.env.REACT_APP_CLIENT_ID_ADMIN
}
export const userPool = CognitoUserPool(poolData_user)
export const adminPool = CognitoUserPool(poolData_admin)
注冊頁面.js
import { userPool, adminPool } from './Userpool'
const SignUpPage = () => {
// This method below will be invoked when user clicks on a Button
const handleButtonClick = () => {
userPool.singUp('someEmail','somePassword',[],null,(err,result)=>{
if(err)
console.error(err)
else
console.log(result)
})
}
return ({/* some JSX which has a button*/})
}
但是當我在SignUpPage.js其中使用該按鈕時,它給了我如下所示的錯誤。

即使我dotenv在我的檔案中使用模塊,也會出現相同的錯誤,如下所示。
用戶池.js
該檔案將保持如上所示相同。
注冊頁面.js
import dotenv from 'dotenv'
import { userPool, adminPool } from './Userpool'
dotenv.config()
const SignUpPage = () => {
// This method below will be invoked when user clicks on a Button
const handleButtonClick = () => {
userPool.singUp('someEmail','somePassword',[],null,(err,result)=>{
if(err)
console.error(err)
else
console.log(result)
})
}
return ({/* some JSX which has a button*/})
}
uj5u.com熱心網友回復:
在運行專案時,您可能需要使用這樣的環境變數(例如 Bash):
REACT_APP_USERPOOL_ID_USER=userId REACT_APP_CLIENT_ID_USER=clientId command_to_start
但是,我想向您推薦一些東西,它幾乎用在我參與過的每個專案中 - dotenv。這樣,您可以避免遇到的問題,并且還可以更輕松地使用環境變數。
這個包允許你有一個名為的檔案.env,你可以在其中定義可以使用process.env. 這有助于其他開發人員通過將所有環境變數放在一個地方來了解您的專案需要哪些環境變數。
它適用于所有環境,例如開發、登臺和生產,因為您可以.env為每個環境擁有一個版本的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360922.html
