繁体   English   中英

如何隐藏通常嵌入在 javascript 文件中的 api 密钥?

[英]How to hide my api key which is normally embedded in a javascript file?

我正在使用来自 rapidapi.com 的 LiveScore api 构建一个小型网站。 部署我的应用程序时如何隐藏我的 api 密钥。 尝试过 env 方法,无服务器方法,但没有太大帮助。 我第一次尝试 api 隐藏方法。 也许这就是我不明白的原因。 有没有什么方法可以隐藏 api 密钥,这相当简单但隐藏得很好?

//索引.js

const options = {
method: 'GET',
headers: {
    'X-RapidAPI-Key': 'xxxxxxxxxx',
    'X-RapidAPI-Host': 'livescore6.p.rapidapi.com'
}
};

fetch('https://livescore6.p.rapidapi.com/matches/v2/list-by-date?   
Category=soccer&Date=20231801&Timezone=-7', options) 
.then(
response => {
    response.json().then(
        data => {
//my code here
})

在普通客户端 Javascript 中,您无法隐藏 API 密钥。 我快速浏览了RapidAPI 文档以及他们的这篇文,但他们只是按原样使用 API 密钥,没有保护任何东西。 (哈哈)

所以如果你担心信息泄露,我建议你用你喜欢的任何后端语言创建一个后端(如果你想使用 Javascript,它可以是 NodeJS)并将它用作代理来发出请求LiveScore API。如果你这样做,你不必在你的客户端代码中硬编码 API 键,你可以在你的后端使用dotenv ,你也可以控制使用哪些端点,甚至添加一些自定义基本身份验证,以便能够一个要求。

这是一个使用 NodeJS 和express的基本示例:

const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');
const app = express();

app.use(express.json());
app.use(cors());

app.get('/api/livescore', async (req, res) => {
  try {
    const options = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Key': process.env.RAPID_API_KEY,
        'X-RapidAPI-Host': process.env.RAPID_API_HOST
      }
    };

    const rapidApiResponse = await fetch('https://some-rapid-api-endpoint.com', options);

    const parsedResponse = await rapidApiResponse.json();

    return res.json({ data: parsedResponse });
  } catch (err) {
    return res.status(500).json({ err: err.message });
  }
});

app.listen(process.env.PORT || 3000);

暂无
暂无

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

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