0

I write a nodejs program to call data form API, it is working if I hard code the API key and token.

Hard code the API key and token is working:

let username = "userid"; //--API_USERNAME
let token = "hfdhdfgfdhgs24" //API TOKEN;
let auth = btoa(`${username}:${token}`);

I store the key and token into .env file , however cannot get the data when calling the API.

It seems cannot read the value from the .env file, would anyone can help?

//.env file
API_USERNAME=userid


//.js code
import dotenv from "dotenv"
dotenv.config();
`var myHeaders = new Headers();
let token = "hfdhdfgfdhgs24" //API TOKEN;

let auth = btoa(`${process.env.API_USERNAME}:${token}`);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jenny Hui
  • 1
  • 1

1 Answers1

0

process.env gives you access to environment variables, i.e. what is exposed to the currently running process.

On Unix-like OS, you can do for example:

export API_USERNAME=myUserName && node ./myScript.js

The .env file is not automatically read by Node. You can use dotenv library to do so: it will look for such file, and inject it into process.env for you:

require('dotenv').config();

let username = process.env.API_USERNAME
ghybs
  • 47,565
  • 6
  • 74
  • 99
  • tried before already before , it not working const dotenv = require('dotenv'); dotenv.config(); console.log(`USER_KEY ${process.env.API_USERNAME}`); let username = process.env.API_USERNAME; – Jenny Hui Jun 14 '23 at 04:02
  • Your `.env` file must be at the root of your project, or you must specify its location in the [`path`](https://github.com/motdotla/dotenv#path) config. If tou need further help, please edit your question to show your file structure and how you call your script. – ghybs Jun 14 '23 at 10:24