简体   繁体   English

如何在API端点中访问Vue.js(或Express)环境变量

[英]How to Access Vue.js (or Express) env variables in an API endpoint

I have a folder called /api in the root of the application where I access an endpoint from the Frontend /src to send an email. 我在应用程序的根目录中有一个名为/api的文件夹,该文件夹可从Frontend /src访问端点以发送电子邮件。 I'd like to call an environment variable here but it is not working with process.env.VUE_APP_APIKEY . 我想在这里调用一个环境变量,但是它不能与process.env.VUE_APP_APIKEY一起使用。 What is the right way to do this? 什么是正确的方法?

This is the endpoint I am calling the env variable from. 这是我从中调用env变量的端点。 This is using express: 这是使用快递:

let endpoint = function(app) {
  app.post('/send-mail', function(req, res) {
    sgMail.setApiKey(process.env.VUE_APP_APIKEY);
    sgMail
      .send(req.body)
      .then(() => {
        // do something
      })
      .catch(error => {
        // do something
      });

    return res.send(req.body);
  });
};

That sgMail is sendgrid, hence the API key I'm calling is for that service. sgMail是sendgrid,因此我正在调用的API密钥用于该服务。

You have to define your env vars somewhere. 您必须在某个地方定义环境变量。 process.env returns an object containing all the user environment. process.env返回包含所有用户环境的对象。

You can define your env vars when you run node , by doing something like this: 您可以在运行node时定义环境变量,方法如下:

MY_VAR=my_value node server.js

An easy way to manage your environment variables with Node.js is to use dotenv . 使用Node.js管理环境变量的一种简单方法是使用dotenv

Create a .env file at the root of your repo or anywhere (depending on your needs) and add your env vars like this: .env的根目录或任何地方(取决于您的需要)创建一个.env文件,并添加如下的env变量:

VUE_APP_APIKEY=[API KEY VALUE]

Then add the following line of code into your server.js or index.js (where your Express is instantiated): 然后将以下代码行添加到server.jsindex.js (实例化Express的位置)中:

require('dotenv').config()

Hence you should be able to use your env vars by using your existing code: process.env.VUE_APP_APIKEY . 因此,您应该能够通过使用现有代码使用process.env.VUE_APP_APIKEY来使用env var。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM