reactjs - 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)
解决方案
您忘记了start:lambda
脚本中的package.json
脚本
"start:lambda": "netlify-lambda serve src/lambda",
参考https://www.gatsbyjs.org/blog/2018-12-17-turning-the-static-dynamic/
推荐阅读
- ios - 遍历 Firebase 数据库并将值分配给变量
- android - Room Android:无法授予线程连接(数据库连接池)
- powershell - 如何从 Powershell 脚本触发 Jenkins 作业?
- android - 在“选择操作”文件上传时显示的 Android PDF 应用程序
- c# - 表asp.net内部的OnClick事件
- pdf - 应用程序池身份和 PDF 生成问题
- ajax - 在完全下载 ReactJS Web 应用程序之前显示加载进度条?
- ruby - “which ruby”指向一个不存在的目录,我如何让它指向与“whereis ruby”相同的目录?
- python - 如何获取行不同的不同列
- javascript - 遍历复杂的嵌套json数组javascript