我正在尝试遵循本教程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)
答案 0 :(得分:1)
您忘记了start:lambda
脚本中的package.json
脚本
"start:lambda": "netlify-lambda serve src/lambda",
ref https://www.gatsbyjs.org/blog/2018-12-17-turning-the-static-dynamic/