【问题标题】:How to hide api key in getInitialProps如何在 getInitialProps 中隐藏 api 密钥
【发布时间】:2020-05-12 18:55:28
【问题描述】:

我尝试将我的 api 客户端与 next.js 连接这是我在 index.js 中代码的一部分

const searchHandler = async(event) => {
const (value === '')return;
Router.push({
pathname: '/zdjatka',
query: {value: 'kotek'}});};

如您所见,我有一些查询参数。触发处理程序后,网站正在路由到我的 zdjatka.js,代码如下,

Test.getInitialProps = async (context) => {
  const { value } = await context.query
const res = await fetch(`https://stock.adobe.io/Rest/Media/1/Search/Files?locale=pl_PL&search_parameters[words]=${value}
    &search_parameters[limit]=22&search_parameters[offset]=22`, {
          headers: {
            "x-api-key": "....",
            "X-Product": "adobe-api/0.1.0",
            "Content-Type": "application/json"
          }
        })
    const data = await res.json()
    // console.log(photos); 
  return {
data: data
  }
}

问题是当我切换到 zdjatka 路由页面时,api 发送请求,chrome 工具在标题中显示我的 api-key,但是当我直接从 webbrowser localhost:3000/zdjatka 打开时,没有来自索引页面的链接,我收到数据的重新请求,女巫在标头中不包含 api-key。与路由器连接时如何达到相同的效果?

【问题讨论】:

  • 您应该将您的 api 密钥保存在后端。

标签: javascript reactjs express fetch next.js


【解决方案1】:

您需要添加next.config.js,并在其中添加:

module.exports = {
  env: {
   apiKey: 'your-api-key',
  },
}

然后在您的 getInitialProps 中,您可以将 API 密钥引用为 process.env.apiKey

【讨论】:

  • 真的吗?如何?但我刚刚意识到你不能真正从客户端隐藏它,你可以运行一个简单的服务器来查询和获取数据,然后将请求发送到你的 api
【解决方案2】:

感谢您的建议,我创建了服务器

const express = require("express");
const next = require("next");
const fetch = require("node-fetch");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
var bodyParser = require("body-parser");
const handle = app.getRequestHandler();

const cors = require("cors");
app
  .prepare()
  .then(() => {
    const server = express();
    server.use(cors());
    server.use(bodyParser.json());
    server.use(bodyParser.urlencoded({ extended: true }));

    server.post("/api", (request, response) => {
      // console.log(request.body);
      const datas = request.body;
      response.json({
        status: "success",
        local: datas.local,
        searchTerm: datas.searchTerm
      });

      server.get('/zdjatka', async (request, response) => {

        // const ROOT_URL = `https://stock.adobe.io/Rest/Media/1/Search/Files?locale=${data.local}&search_parameters[word]=${data.searchTerm}&search_parameters[limit]=22&search_parameters[offset]=22`;
        const url =
          "https://stock.adobe.io/Rest/Media/1/Search/Files?locale=pl_PL&search_parameters[words]=kotek&search_parameters[limit]=22&search_parameters[offset]=22";
        const fetchData = await fetch(url, {

          headers: {
            "x-api-key": "....",
            "X-Product": "adobe-api/0.1.0",
            "Content-Type": "application/json",
            "Accept": "application/json"
          }
        });
             console.log(response.status);
         const data = await fetchData.json();
        response.json(data);
          console.log(response);    
        console.log(json);           

      })
    });

并从页面请求

 const searchHandler = async (event) => {
// Router.router.push('/zdjatka');
setSearchTerm(event.target.value);
   const data = ({local: "pl_PL",
   searchTerm: searchTerm });

const options = {
     method: "POST",
     headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
      },
     body: JSON.stringify(datas)
    }
     const response = await fetch('/api', options);
     const json = await response.json();
    console.log(json);
 const fetchData = await fetch('/zdjatka', {

     headers: {
     'Content-Type': 'application/json',
    'Accept': 'application/json'
       }
     });

       console.log(response)
     const data = await fetchData.json();
       console.log(data);                      

  }

向服务器发送请求的第一部分工作正常,但我无法从外部 api 获得响应。 我会非常感谢任何建议!如何通过服务器处理这个管道请求响应。

问题解决了,我想念 try / catch。

【讨论】:

    猜你喜欢
    • 2021-01-27
    • 2020-04-15
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2020-09-28
    相关资源
    最近更新 更多