在这两种情况下,环境变量都会对您有所帮助。您可以使用dotenv库。代码示例被简化以专注于您的问题。
- 假设您的 React 应用程序向后端端点( localhost:9000/endpoint )发出请求,该端点将从第三方服务(在本例中使用got库)请求数据,您将从环境变量中获取 auth 密钥:
require('dotenv').config(); // init env vars
const got = require('got');
const express = require('express');
const router = express.Router();
// getting API key from env variable
const apiKey = process.env.AUTH_KEY;
// GET localhost:9000/endpoint
router.get('/endpoint', async (req, res) => {
// requesting data from 3rd party service
const response = await got('https://thirdpartyservice.com/api', {
headers: {
'x-auth-token': apiKey, // the auth token header
json: true, // assuming response will be "application/json"
},
});
// passing data to React
res.json(JSON.parse(response));
});
- 您还应该将后端服务 URL 存储在环境变量中。您可能有两个 .env 文件分别用于开发和生产环境:
发展:
# .env file on your localhost
AUTH_KEY = <your_secret_key>
API_URL=localhost:9000/
生产:
# env vars on heroku
AUTH_KEY = <your_secret_key>
API_URL=<api_server_name>.herokuapp.com/
并将 URL 传递给您的 React 应用程序:
require('dotenv').config(); // init env vars
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// your api server URL from env vars
const apiUrl = process.env.API_URL;
// pass the api URL to your React app
ReactDOM.render(
<App apiUrl={ apiUrl } />,
document.getElementById('root'),
);