Setting up environment variables in node, specific

2019-08-21 03:47发布

I have a node application and I'm trying to use the google language api. I want to set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the json file in the same directory (sibling to package.json and app.js).

I had tried process.env.GOOGLE_APPLICATION_CREDENTIALS = "./key.json"; in my app.js file (using express), but it isn't working. I have also tried putting "GOOGLE_APPLICATION_CREDENTIALS":"./key.json" in my package.json and that didn't work as well. It DOES work when I run in the terminal export GOOGLE_APPLICATION_CREDENTIALS="./key".

Here is the error message:

ERROR: Error: Unexpected error while acquiring application default credentials: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information.

Any tips are appreciated, thanks!

3条回答
聊天终结者
2楼-- · 2019-08-21 04:28

It could be that the environment variable in you OS was not set. For example in Linux you usually have to set GOOGLE_APPLICATION_CREDENTIALS in the terminal where you executed your app.

 export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Another option you have is passing the json path by code. It is documented this process using Node.js with the Cloud Storage.

查看更多
smile是对你的礼貌
3楼-- · 2019-08-21 04:32

The GOOGLE_APPLICATION_DEFAULT environment variable you are setting is accessed by the google client libraries - it wont work with a relative path, you'll need to set the absolute path.

查看更多
Fickle 薄情
4楼-- · 2019-08-21 04:47

After reading an reading about this issue on internet, the only way to resolve this issue for me was declare de environmental variable for the node execution:

GOOGLE_APPLICATION_CREDENTIALS="./key.json" node index.js

Because I was able to print the token from my server console, but when I was running the node application, the library was unable to retrieve the system environment value, but setting the variable for the execution it was able to retrieve the value.

查看更多
登录 后发表回答