0

我一直在尝试设置一个无服务器功能来在我的 Gatsby 网站上发送电子邮件。该功能正在托管,但每当我尝试获取它时,它都会告诉我它不存在。

我的获取:

const body = {
  name,
  email,
  phone,
  message,
};

fetch(`http://localhost:8000/.netlify/functions/sendMail`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(body),
})
  .then((res) => console.log(res.data))
  .catch((err) => console.error(err));

中间件gatsby-config.js

developMiddleware: (app) => {
  app.use(
    "/.netlify/functions/",
    createProxyMiddleware({
      target: "http://localhost:8000",
      pathRewrite: {
        "/.netlify/functions/": "",
      },
    })
  );
},

函数路径:

    • 功能
      • 发邮件
        • 节点模块
        • 包.json
        • 发送邮件.js
        • 纱线锁

我认为这与我在fetch()函数中使用的 url 有关。

4

1 回答 1

1

If you're using netlify-lambda serve <functions folder> to compile and serve your functions in development, you need to set your target to the port that the netlify-lambda listener is bound on, which is 9000 by default. Right now you're redirecting to port 8000, which appears to be the port your Gatsby app is running on.

So, for example, you want your set up to look more like this:

  // Forward Netlify Function requests to `netlify-lambda` server
  // when the development server is running.
  developMiddleware: app => {
    app.use(
      "/.netlify/functions/",
      proxy({
        target: "http://localhost:9000", // <--- Port that `netlify-lambda` is using
        pathRewrite: {
          "/.netlify/functions/": "",
        },
      })
    )
  },
于 2021-03-12T21:19:20.590 回答