如何将数据传递给 Fauna Create 函数

How do I pass data to a Fauna Create function

我正在构建 Next 站点并决定使用 Fauna 作为我的数据库。在 front-end 上,我正在将 object 传递给我的 back-end API,如下所示:

  async function onSubmit(values) {
    try {
      const data = await postData("/api/put", values);
    } catch (error) {
      console.error(error);
    }

    async function postData(url = "", data = {}) {
      const response = await fetch(url, {
        method: "POST",
        mode: "cors",
        cache: "no-cache",
        credentials: "same-origin",
        headers: {
          "Content-Type": "application/json"
        },
        redirect: "follow",
        referrer: "no-referrer",
        body: JSON.stringify(data)
      });

      return await response.json(); // parses JSON response into native JavaScript object
    }
  }

我的 back-end 看起来像这样:

const faunadb = require("faunadb");

// your secret hash
//! -- Replace with secret for prod.
const secret = "Key...";
const q = faunadb.query;
const client = new faunadb.Client({ secret });

module.exports = async (req, res) => {
  const data = JSON.stringify(req.body, null, 2);
  console.log(data);
  return client
    .query(
      q.Create(q.Collection("pages"), {
        data: {
          name: data.name,
          email: data.email,
          title: data.title,
          body: data.body
        }
      })
    )
    .then(ret => console.log(ret))
    .catch(err => console.log("error", err));
};

似乎在 return 中,data 未被识别,并且发送回 Fauna collection 的项目是空的。有人可以告诉我我做错了什么吗?

Fauna Docs 不显示带有变量的示例。

我将代码更改为以下内容:

module.exports = async (req, res) => {
  console.log(req.body.name);
  const bodyData = JSON.stringify(req.body, null, 2);
  // console.log(bodyData);
  return client
    .query(
      q.Create(q.Collection("pages"), {
        data: {
          name: req.body.name,
          email: req.body.email,
          title: req.body.title,
          body: req.body.body
        }
      })
    )
    .then(ret => console.log(ret))
    .catch(err => console.log("error", err));
};

现在运行良好!