【问题标题】:How to insert params into netlify functions?如何将参数插入 netlify 函数?
【发布时间】:2020-11-11 02:25:37
【问题描述】:

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

script.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);
});

token-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。

【问题讨论】:

    标签: javascript serverless netlify jamstack netlify-function


    【解决方案1】:

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

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

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

    1. 您的代码获取了查询字符串参数,看起来您只需将它们添加到您点击的 URL 的末尾。你试过了吗?

    【讨论】:

      猜你喜欢
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      相关资源
      最近更新 更多