如何将查询参数传递给lambda函数(netlify环境)内部的url

时间:2019-04-27 07:44:18

标签: reactjs api lambda netlify

当用户提交搜索表单时,我想将查询参数添加到lambda函数内部的api网址中。

我在React应用程序中设置了netlify环境并初始化了一个lambda函数。现在我只能通过硬编码的查询来获得响应。

如何将参数传递给event.queryStringParameters?

exports.handler = function(event, context, callback) {
  const API_PARAMS = qs.stringify(event.queryStringParameters);
  const { API_TOKEN, API_URL } = process.env;
  const URL = `${API_URL}search?part=snippet&maxResults=5&key=${API_TOKEN}&q=animals`;

  // Let's log some stuff we already have.
  console.log("Injecting token to", API_URL);
  console.log("logging event.....", event);
  console.log("Constructed URL is ...", URL);
  console.log('params are...', API_PARAMS);

  const pass = body => {
    callback(null, {
      statusCode: 200,
      body: JSON.stringify(body)
    });
  };

  const get = () => {
    axios
      .get(URL)
      .then(response => {
        console.log(response.data);
        pass(response.data);
      })
      .catch(err => pass(err));
  };
  if (event.httpMethod == "GET") {
    get();
  }
};

App.js

  componentDidMount() {
    fetch('.netlify/functions/youtube')
     .then(response => response.json())
     .then(data => console.log(data));
  }

1 个答案:

答案 0 :(得分:1)

这花了我一分钟时间,但它在查询字符串中:

   let thing = 123;
   fetch(`/.netlify/functions/${filename}?item=${thing}`)
      .then(response => response.json())
      .then(json => console.log(json))

如果是帖子,则需要从查询中解析它,但是常规的get调用可以将其拉出event.queryStringParameters