0

I've been trying to set up a serverless function for sending emails in my Gatsby website. The function is being hosted, but whenever I try to get it, it tells me that it doesn't exist.

My fetch:

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));

Middleware in gatsby-config.js:

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

Function path:

  • root
    • functions
      • sendMail
        • node_modules
        • package.json
        • sendMail.js
        • yarn.lock

I think it has something to do with the url I am getting it with in my fetch() function.

1 Answers1

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/": "",
        },
      })
    )
  },
coreyward
  • 77,547
  • 20
  • 137
  • 166