0

我有一个输入,它在提交到 unsplash API 时发送一个 api 调用。我正在尝试将其转换为 netlify 函数,但不确定如何将参数从输入传递到函数中。我正在尝试隐藏 API 密钥。我从来没有使用过 qs 包并查找了文档,但还没有完全弄清楚。

脚本.js

const KEY = "" //secret
const URL = `https://api.unsplash.com/search/photos?page=1&per_page=50&client_id=${process.env.KEY}`;
const input = document.querySelector(".input");
const form = document.querySelector(".search-form");
const background = document.querySelector(".background");
const overlay = document.querySelector(".overlay");
const header = document.querySelector(".title");
let results = [];

search = (searchTerm) => {
  let url = `${URL}&query=${searchTerm}`;//this should hit the netlify endpoint instead
  return fetch(url)
    .then((response) => response.json())
    .then((result) => {
      toggleStyles();
      header.appendChild(form);
      result.results.forEach((image) => {
        const galleryItem = document.createElement("div");
        galleryItem.className = "gallery-item";
        const imageDiv = document.createElement("div");
        imageDiv.className = "image-div";
        document.querySelector(".results-page").appendChild(galleryItem);
        galleryItem.appendChild(imageDiv);
        imageDiv.innerHTML =
          "<img class='image' src=" + image.urls.regular + ">";
        form.classList.remove("toggle-show");
        input.classList.add("header-expanded");
        form.addEventListener("submit", (e) => {
          e.preventDefault();
          document.querySelector(".results-page").remove();
        });
      });

      console.log(result.results);
      return results;
    });
};

toggleStyles = () => {
  const resultsContainer = document.createElement("div");
  resultsContainer.className = "results-page";
  document.body.appendChild(resultsContainer);
};

input.addEventListener("focus", (e) => {
  e.preventDefault();
  input.style = "font-family: 'Raleway', sans-serif";
  input.placeholder = "";
});

input.addEventListener("blur", (e) => {
  e.preventDefault();
  input.style = "font-family: FontAwesome";
  input.value = "";
  input.placeholder = "\uf002";
});

form.addEventListener("submit", (e) => {
  e.preventDefault();
  let searchTerm = input.value;
  search(searchTerm);
});

令牌-hider.js

const axios = require("axios");
const qs = require("qs");

exports.handler = async function (event, context) {
  // apply our function to the queryStringParameters and assign it to a variable
  const API_PARAMS = qs.stringify(event.queryStringParameters);
  console.log("API_PARAMS", API_PARAMS);
  // Get env var values defined in our Netlify site UI

  // TODO: customize your URL and API keys set in the Netlify Dashboard
  // this is secret too, your frontend won't see this
  const { KEY } = process.env;
  const URL = `https://api.unsplash.com/search/photos?page=1&per_page=50&client_id=${KEY}`;

  console.log("Constructed URL is ...", URL);

  try {
    const { data } = await axios.get(URL);
    // refer to axios docs for other methods if you need them
    // for example if you want to POST data:
    //    axios.post('/user', { firstName: 'Fred' })
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (error) {
    const { status, statusText, headers, data } = error.response;
    return {
      statusCode: error.response.status,
      body: JSON.stringify({ status, statusText, headers, data }),
    };
  }
};

我在我的 netlify UI 中添加了 KEY 作为环境变量,并且能够访问函数的端点。非常感谢任何帮助,因为我是无服务器功能的新手,但非常想学习 JAMstack。

4

1 回答 1

1

我认为您在这里问了两个不同的问题-如何在 Netlify 函数中使用密钥以及如何从前端代码向其传递参数。

  1. 您可以在 Netlify 站点设置中定义环境变量。这些变量然后可以通过在您的 Netlify 函数中使用process.env。因此,如果您调用变量 SECRET_KEY,那么您的 Netlify 函数代码(不是您的前端代码!)将能够通过process.env.SECRET_KEY.

查看您的代码,您似乎理解了这一点,因为您在函数中拥有它,但您尝试在客户端代码中使用它。你可以删除它。

  1. 您的代码获取查询字符串参数,看起来您只需将它们添加到您点击的 URL 的末尾。你试过吗?
于 2020-07-23T14:47:22.273 回答