1

这个 Netlify 函数应该作为端点运行,example.com/.netlify/functions/github并且应该代理来自我的网站的获取请求,访问 GitHub API 并将数据发送回网站。

据我了解,我可以使用从 GitHub API 获取数据而无需身份验证。直接在浏览器中访问他们的 API 是可行的:https ://api.github.com/orgs/github/repos?per_page=2 (也适用于 Postman)。

数据是一个对象数组,其中每个对象都是一个存储库。

在过去的几年里,Netlify 函数(在 AWS lambdas 上运行)出现了多个问题,这些问题导致了类似于我的错误消息,所以我很困惑这是我的代码中的错误还是他们身边的一些奇怪的东西.

首先,根据 Netlify 管理控制台,代理功能运行无误。在支持文章中, Netlify 要求返回的结果为JSON.stringify(),因此我在此处遵循该约定:


const fetch = require('node-fetch')
const url = 'https://api.github.com/orgs/github/repos?per_page=2'

const optionsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type'
}

const fetchHeaders = {
  'Content-Type': 'application/json',
  'Host': 'api.github.com',
  'Accept': 'application/vnd.github.v3+json',
  'Accept-Encoding': 'gzip, deflate, br'
}

exports.handler = async (event, context) => {
  if (event.httpMethod === 'OPTIONS') {
    return {
      'statusCode': '200',
      'headers': optionsHeaders,
    }

  } else {

    try {
      const response = await fetch(url, {
        method: 'GET',
        headers: fetchHeaders
      })

      const data = await response.json()
      console.log(JSON.stringify({ data }))

      return {
        statusCode: 200,
        body: JSON.stringify({ data })
      }

    } catch (err) {
      console.log(err)
    }
  }
}

命中的客户端获取https://example.com/.netlify/functions/github。URL 正确,函数执行(在 Netlify 管理面板中验证):

const repos = document.querySelectorAll('.repo')

if (repos && repos.length >= 1) {
  const getRepos = async (url) => {
    try {
      const response = await fetch(url, {
        method: "GET",
        mode: "no-cors"
      })
      
      const res = await response.text() 
      // assuming res is now _text_ as per `JSON.stringify` but neither 
      // that nor `.json()` work

      console.log(res[0].name)
      return res[0].name

    } catch(err) {
      console.log(err)
    }
  }

  const repoName = getRepo('https://example.com/.netlify/functions/github')
  
  repos.forEach((el) => {
    el.innerText = repoName
  })
}

不能 100% 确定此错误消息的来源,虽然它显示在浏览器控制台中,但它可能不是 console.log(err),因为错误代码是502,并且错误也直接显示在 Postman 的响应正文中。

error decoding lambda response: error decoding lambda response: json: cannot unmarshal
string into Go value of type struct { StatusCode int "json:\"statusCode\""; Headers
 map[string]interface {} "json:\"headers\""; MultiValueHeaders map[string][]interface {}
 "json:\"multiValueHeaders\""; Body string "json:\"body\""; IsBase64Encoded bool 
"json:\"isBase64Encoded,omitempty\""; Metadata *functions.Metadata 
"json:\"metadata,omitempty\"" }

还没有找到任何关于这个问题的明确信息,请各位大神赐教?

4

1 回答 1

3

唯一不符合架构的响应是预检请求。从错误消息中,我假设您需要更改:

'statusCode': '200',

'statusCode': 200, // StatusCode int

更好的是,因为没有内容,您可能想要使用它204。如果这还不够,我可能还想在其中包含正文,因为它似乎不是可选的:

    return {
      'statusCode': 204,
      'headers': optionsHeaders,
      'body': ''
    }
于 2021-08-19T00:19:34.437 回答