【发布时间】:2021-03-23 05:28:07
【问题描述】:
我不太确定此类事情的最佳实践,但我有一个简单的网页,其中包含 index.html、style.css 和 scripts.js,我在其中调用 Spotify API。我还有一个server.js,我在其中运行我的 Node.js 服务器。
为了调用 Spotify API,我需要提供我的客户端 ID,我将其作为环境变量存储在我的 .env 中。基本上我是从前端进行 API 调用,但需要从后端获取环境变量。有没有办法将环境变量从server.js 传递给scripts.js,或者能够直接从scripts.js 访问环境变量,或者我需要重组我的应用程序吗?
如果我能提供更多信息,请告诉我!
server.js
require('dotenv').config();
const express = require('express');
const app = express();
const path = require('path');
const port = 3000;
app.use(express.static('public'));
app.get('/', (req, res) => {
res.setHeader('Content-Type', 'text/html');
res.sendFile(path.join(__dirname, 'public/index.html'));
});
app.listen(port, () => {
console.log(`Listening at port ${port}`);
})
scripts.js
...
function getAccess() {
const responseType = 'token';
const CLIENTID = process.end.CLIENT_ID;
let redirect = `https://accounts.spotify.com/authorize?response_type=${responseType}&client_id=${CLIENTID}&scope=${scopes}&redirect_uri=${redirectUri}`;
window.location = redirect;
}
...
【问题讨论】:
标签: javascript node.js environment-variables dotenv