`process.env.CLIENT_ID`在函数中可用,但在Express中不可用作全局变量。

huangapple go评论74阅读模式
英文:

process.env.CLIENT_ID works in function but not as a global variable in Express

问题

我正在尝试使用OAuth与Google API一起工作。

我正在使用.env文件来存储秘密变量,并通过.gitignore来隐藏它们。

我的问题是,如果我尝试在函数外部定义如下:

CLIENT_ID = process.env.CLIENT_ID

作为全局变量,当我运行这个变量并将其打印到控制台时,它返回undefined。

然而,如果我尝试在函数内部之外定义它并在函数内部打印它,它会显示undefined

如果我像这样设置我的控制器文件,它可以工作:

const passport = require('passport')
const validator = require('validator')
const User = require('../models/User')
const Company = require('../models/Company')
const { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
const axios = require('axios');
const auth = require('../middleware/auth');
const dayjs = require('dayjs')

exports.googleAuthCode = (req, res) => {
  let CLIENT_ID = process.env.CLIENT_ID;
  let CLIENT_SECRET = process.env.CLIENT_SECRET;
  let REDIRECT_URL =  process.env.REDIRECT_URL;

  const SCOPES = 'https://www.googleapis.com/auth/calendar';
  const oAuth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URL,
  );

  console.log('running googleAuthCode')
  console.log('process.env.CLIENT_ID ', process.env.CLIENT_ID)
  console.log('process.env.CLIENT_SECRET ', process.env.CLIENT_SECRET)
  console.log('process.env.REDIRECT_URL ', process.env.REDIRECT_URL)
  console.log('CLIENT_ID ', CLIENT_ID)
  console.log('CLIENT_SECRET ', CLIENT_SECRET)
  console.log('REDIRECT_URL ', REDIRECT_URL)

  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('authURL: ', authUrl)
  res.redirect(authUrl);
}

如果我像这样设置我的控制器,它就无法工作:

const passport = require('passport')
const validator = require('validator')
const User = require('../models/User')
const Company = require('../models/Company')
const { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
const axios = require('axios');
const auth = require('../middleware/auth');
const dayjs = require('dayjs')

let CLIENT_ID = process.env.CLIENT_ID;
let CLIENT_SECRET = process.env.CLIENT_SECRET;
let REDIRECT_URL =  process.env.REDIRECT_URL;

const SCOPES = 'https://www.googleapis.com/auth/calendar';
const oAuth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URL,
);

exports.googleAuthCode = (req, res) => {
  console.log('running googleAuthCode')
  console.log('process.env.CLIENT_ID ', process.env.CLIENT_ID)
  console.log('process.env.CLIENT_SECRET ', process.env.CLIENT_SECRET)
  console.log('process.env.REDIRECT_URL ', process.env.REDIRECT_URL)
  console.log('CLIENT_ID ', CLIENT_ID)
  console.log('CLIENT_SECRET ', CLIENT_SECRET)
  console.log('REDIRECT_URL ', REDIRECT_URL)

  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('authURL: ', authUrl)
  res.redirect(authUrl);
}

我正在使用dotenv。

我正在使用MVC设置,

require('dotenv').config({ path: './config/.env' })

在我的server.js文件中,并导出到我的控制器文件中。

如果你能解释一下如何将它作为全局变量使其正常工作,我将不胜感激。

英文:

I am trying to use oAuth to work with googleapi

I am using .env to keep secret variables hidden with .gitignore

My problem is that if I try to define

CLIENT_ID = process.env.CLIENT_ID 

Outside of the function as a global variable, when I run the variable and console log it, it returns undefined.

However, if I try to define it outside of the function and console log it inside it shows undefined

If I set my controller file like this it works

const passport = require('passport')
const validator = require('validator')
const User = require('../models/User')
const Company = require('../models/Company')
const { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
const axios = require('axios');
const auth = require('../middleware/auth');
const dayjs = require('dayjs')



  exports.googleAuthCode = (req, res) => {

   let CLIENT_ID = process.env.CLIENT_ID;
   let CLIENT_SECRET = process.env.CLIENT_SECRET;
   let REDIRECT_URL =  process.env.REDIRECT_URL;


   const SCOPES = 'https://www.googleapis.com/auth/calendar';
   const oAuth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URL,


  );

    console.log('running googleAuthCode')

    console.log('process.env.CLIENT_ID ', process.env.CLIENT_ID)
    console.log('process.env.CLIENT_SECRET ', process.env.CLIENT_SECRET)
    console.log('process.env.REDIRECT_URL ', process.env.REDIRECT_URL)
    console.log('CLIENT_ID ', CLIENT_ID)
    console.log('CLIENT_SECRET ', CLIENT_SECRET)
    console.log('REDIRECT_URL ', REDIRECT_URL)


    const authUrl = oAuth2Client.generateAuthUrl({
      
      access_type: 'offline',
      scope: SCOPES,
    });
    console.log('authURL: ',authUrl)
    res.redirect(authUrl);


  }

If I set my controller like this it doesn't work:


const passport = require('passport')
const validator = require('validator')
const User = require('../models/User')
const Company = require('../models/Company')
const { google } = require('googleapis');
const { OAuth2Client } = require('google-auth-library');
const axios = require('axios');
const auth = require('../middleware/auth');
const dayjs = require('dayjs')

   let CLIENT_ID = process.env.CLIENT_ID;
   let CLIENT_SECRET = process.env.CLIENT_SECRET;
   let REDIRECT_URL =  process.env.REDIRECT_URL;


   const SCOPES = 'https://www.googleapis.com/auth/calendar';
   const oAuth2Client = new google.auth.OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URL,


  );

  exports.googleAuthCode = (req, res) => {

   

    console.log('running googleAuthCode')

    console.log('process.env.CLIENT_ID ', process.env.CLIENT_ID)
    console.log('process.env.CLIENT_SECRET ', process.env.CLIENT_SECRET)
    console.log('process.env.REDIRECT_URL ', process.env.REDIRECT_URL)
    console.log('CLIENT_ID ', CLIENT_ID)
    console.log('CLIENT_SECRET ', CLIENT_SECRET)
    console.log('REDIRECT_URL ', REDIRECT_URL)


    const authUrl = oAuth2Client.generateAuthUrl({
      
      access_type: 'offline',
      scope: SCOPES,
    });
    console.log('authURL: ',authUrl)
    res.redirect(authUrl);


  }

I am using dotenv

I am using MVC setup,

require('dotenv').config({path: './config/.env'})

Is in my server.js file and exported to my controller file.

If you can shed some light on to how i can get this working as a global variable it would be very much appreciated.

答案1

得分: 0

确保在所有其他模块之上导入dotenv

假设我有两个文件在我的项目中:main.jsutils.js

// main.js
const { func1 } = require('./utils.js');
require('dotenv').config();
func1();
// utils.js
console.log(process.env.SOME_SECRET);

exports.func1 = function() {
  console.log(process.env.SOME_SECRET);
}

在这种情况下,结果将是这样的:

undefined
SECRET

原因是在解释器开始并解释每一行的时候,全局环境变量是undefined,在解释和处理dotenv模块之后,环境变量存储在RAM中并获得值。

因此,在执行func1的最后一行时,环境变量具有值。

这就是为什么建议在主文件的第一行导入dotenv的原因。

所以正确的方式应该是这样的:

// main.js
require('dotenv').config();
const { func1 } = require('./utils.js');
func1();
英文:

Make sure that dotenv is imported above all other modules.

Assume that I have two files inside my project: main.js and utils.js.

// main.js
const { func1 } = require('./utils.js');
require('dotenv').config();
func1();
// utils.js
console.log(process.env.SOME_SECRET);

exports.func1 = function() {
  console.log(process.env.SOME_SECRET);
}

In this case, the result would be like this:

undefined
SECRET

The reason is that at the moment when the interpreter starts and interprets each line, the global env variable is undefined, and after the dotenv module is interpreted and processed, the environment variables sit in RAM and get values.

Therefore, in the last line where func1 is executed, the environment variable has value.

That's why it is recommended to import dotenv at the very first line in the main file.

So the correct way would be like this:

// main.js
require('dotenv').config();
const { func1 } = require('./utils.js');
func1();

答案2

得分: 0

感谢您的帮助!

答案是正确的,我必须将 dotenv 导入到我想要的控制器文件中。

但我必须按照以下格式执行:

const dotenv = require('dotenv');
dotenv.config({path: './config/.env'})

一旦我添加了路径,它就可以正常工作,没有问题!

英文:

Thank you for your help!

The answers were right that I dad to import dotenv into the controller file that I wanted.

But I had to do it in the format

const dotenv = require('dotenv');
dotenv.config({path: './config/.env'})

Once I added the path it worked no problem!

huangapple
  • 本文由 发表于 2023年1月7日 20:37:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75040386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定