首页 > 解决方案 > 如何在 lambda 函数 fetch 中导入值?

问题描述

在用户输入城市名称后,我必须调用此 API 以推断我将操作的响应。

API 使用了一个密钥,我将其隐藏在一个 env 文件中。整个使用Netlify作为主机。

index.js

async function checkAir() {
    
let cityName = document.getElementById("cityName").value; // value of the city in form 

// Call API
const response = await fetch("/.netlify/functions/lambda") 
const result = await response.json()
// console.log(response)
console.log(result)
}

lambda.js

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

exports.handler = async event => {
  const apiKey =  process.env.apiKey

  const response = await fetch(`https://api.waqi.info/feed/${cityName}/?token=${apiKey}`)
  const result = await response.json() 

  const pass = (result) => {
    return {
      statusCode: 200,
      body: JSON.stringify(result)
    }
  }

  return pass(result)
}

为了拨打电话并隐藏密钥,我使用了 lambda 函数。因此 index.js 调用 lambda.js,它发出调用并将响应提供给操纵它的 index.js。

如何确保输入的城市值(“cityName”)作为 lambda 函数 fetch 中的变量导入?

所以这个电话给了我错误: cityName undefined

标签: javascriptnode.jslambda

解决方案


推荐阅读