Netlify Functions in Gatsby JS



我正在尝试按照本教程进行操作 https://www.gatsbyjs.org/blog/2018-12-17-turning-the-static-dynamic/

我安装了依赖项,这似乎很好。我在我的包中添加了必要的脚本.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以添加developMiddleWare部分和此处看到的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),
      }),
    })
  }

最后在我的索引.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) 

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

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

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

最新更新