0

Hi!,

First of all, I just wanted to thank you for the fantastic courses you put out. They have been a great help to my learning.

I am having trouble getting the user registration to post to Sanity.io. I see that many other folks in the comments have had the same problem, so I was hoping maybe a solution has been found? I have tried to troubleshoot my self for many hours, but I can’t seem to figure out the issue. I have made sure that my code matches yours in the necessary places, etc. I have attempted to console.log to find the error. It seems to me that the request is not even hitting the next/api..

I have used Postman to return a get request from the users api successfully.

I would really appreciate any help!

Here is a snippet of code from the register.js front end page:

const submitHandler = async ({
    firstName,
    lastName,
    email,
    password,
    confirmPassword,
  }) => {
    if (password !== confirmPassword) {
      enqueueSnackbar("Passwords don't match", { variant: "error" });
      return;
    }
    try {
      const { data } = await axios.post(`/api/users/register`, {
        firstName,
        lastName,
        email,
        password,
      });
      console.log("hit success")
      dispatch({ type: "USER_LOGIN", payload: data });
      jsCookie.set("userInfo", JSON.stringify(data));
      router.push("/");
    } catch (err) {
      console.log(err.message)
      enqueueSnackbar("Something went wrong, please try again.", { variant: "error" });
    }
  };

Here is the code from my api/users/router.js file:

handler.post(async (req, res) => {
  console.log("hit handler")
  const projectId = client.projectId;
  const dataset = client.dataset;
  const apiVersion = client.apiVersion;
  const tokenWithWriteAccess = process.env.SANITY_AUTH_TOKEN;
  const createMutations = [
    {
      create: {
        _type: "user",
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
        password: bcrypt.hashSync(req.body.password),
        isAdmin: false,
        isWholesale: false,
      },
    },
  ];
  const { data } = await axios.post(
    `https://${projectId}.api.sanity.io/v${apiVersion}/data/mutate/${dataset}`,
    {
      mutations: createMutations,
    },
    {
      headers: {
        "Content-type": "application/json",
        Authorization: `Bearer ${tokenWithWriteAccess}`,
      },
    }
  );
  const userId = data.results[0].id;
  const user = {
    _id: userId,
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    email: req.body.email,
    isWholesale: false,
    isAdmin: false,
  };
   const token = signToken(user);
  res.send({ ...user, token });
});

Thank you in advance for your time!

Best,

Zach

Calathea Asked question April 15, 2023