首页 > 解决方案 > Gatsby JS 中的 Netlify 函数

问题描述

我正在尝试遵循本教程https://www.gatsbyjs.org/blog/2018-12-17-turning-the-static-dynamic/

我安装了依赖项,这似乎很好。我在我的 package.json 中添加了必要的脚本,这是我目前的脚本

"scripts": {
    "build": "gatsby build && netlify-lambda build src/lambda",
    "start": "run-p start:**",
    "start:app": "npm run develop",
    "develop": "gatsby develop",
    "build:app": "gatsby build",
    "build:lambda": "netlify-lambda build src/lambda",
    "format": "prettier --trailing-comma es5 --no-semi --single-quote --write \"src/**/*.js\""
  },

我在根目录下添加了 netlify.toml。

我附加了我的 gatsby-config.js 来添加 developerMiddleWare 部分和这里看到的 var 代理

require('dotenv').config()
var proxy = require("http-proxy-middleware")


module.exports = {
  siteMetadata: {
    title: `Creative Portfolio`,
  },
  developMiddleware: app => {
    app.use(
      "/.netlify/functions/",
      proxy({
        target: "http://localhost:9000",
        pathRewrite: {
          "/.netlify/functions/": "",
        },
      })
    )
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-sass`,
    `gatsby-transformer-remark`,
    {
      resolve: `gatsby-source-datocms`,
      options: {
        apiToken: process.env.DATO_API_TOKEN,
      },
    },
  ],
  
}

然后我在 src/lambda/hello.js 中制作了以下文件

// For more info, check https://www.netlify.com/docs/functions/#javascript-lambda-function
export function handler(event, context, callback) {
    console.log("queryStringParameters", event.queryStringParameters)
    callback(null, {
      // return null to show no errors
      statusCode: 200, // http status code
      body: JSON.stringify({
        msg: "Hello, World! " + Math.round(Math.random() * 10),
      }),
    })
  }

最后在我的 index.js 页面上,我添加了一个按钮来获取响应。

function handleClick(e) {
    fetch("/.netlify/functions/hello")
  .then(response => response.json())
  .then(console.log)
  }

组件中的按钮

<a href="#" onClick={handleClick}
      Click me
    </a>>

现在对于结果,当我运行 yarn start 时,终端中的代理获得了以下成功。

info [HPM] Proxy created: /  -> http://localhost:9000
info [HPM] Proxy rewrite rule created: "/.netlify/functions/" ~> ""

当我单击按钮时,我的控制台中出现以下错误。

GET http://localhost:8000/.netlify/functions/hello 504 (Gateway Timeout)
Uncaught (in promise) SyntaxError: Unexpected token E in JSON at position 0 

希望有人可以帮助我解决这个问题。

我的控制台中也出现以下错误

[HPM] Error occurred while trying to proxy request hello from localhost:8000 to http://localhost:9000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors) 

标签: reactjsaws-lambdagatsbynetlify

解决方案


您忘记了start:lambda脚本中的package.json脚本

"start:lambda": "netlify-lambda serve src/lambda",

参考https://www.gatsbyjs.org/blog/2018-12-17-turning-the-static-dynamic/


推荐阅读