Shopify / shopify-app-template-node

MIT License
860 stars 393 forks source link

POST Request Body sent with Fetch is empty #1329

Closed oxsmose closed 1 month ago

oxsmose commented 1 month ago

The nodes backend receives empty body when data is sent with useAuthenticatedFetch POST query.

Part of the code in client:

import { useAppQuery, useAuthenticatedFetch } from "../hooks";

const fetch = useAuthenticatedFetch();
const handleSubmit = async (event) => {

        setIsLoading(true);
        const data = {
            title: "test",
        };

        const response = await fetch("/api/layer", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        });

        if (response.ok) {
            showMessage("Layer saved");
            setIsLoading(false);
        } else {
            toggleActive();
            showError("Error while saving");
            setIsLoading(false);
        }
    }

Server side:

const app = express();
app.use(express.json());

app.post("/api/layer", async (_req, res) => {
  let status = 200;
  let error = null;
  //console.log('Received headers:', _req.headers);
  console.log('Received body:', _req.body);
  console.log('Received body:', _req.query);
  console.log('Received body:', _req);
  try {
    //const client = new shopify.api.clients.Graphql({ session });

    let bblayers = await db.collection("collectiondbname");
    const doc = {
      title: "Record of a Shriveled Datum",
      bboxlayerId: res.locals.shopify.session.shop
    }
    // Insert the defined document into the "haiku" collection
    const result = await bblayers.insertOne(doc);
  } catch (e) {
    status = 500;
    error = e.message;
  }

  res.status(status).send({ success: status === 200, error });
});

I tried on an other route than api to revert back to the Fetch js vanilla code. Same issue. I tried to use "body-parser" with no more success. I tried formData with "express.urlencoded({ extended: true })" with no more success.

Steps to reproduce the problem

  1. write a test code that send a post request in nodes server and log the req.body. I got empty value.
oxsmose commented 1 month ago

Finally it works with the following code:

const data = {
            title: title,
        };

        const formBody = new URLSearchParams(data).toString();

        const response = await fetch("/api/layer", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formBody
        });

And Json definitly not working.

lizkenyon commented 1 month ago

Hi there 👋

I am glad you figured it out.

If you are just starting out building apps I would recommend looking into our Remix template. We believe it has a better developer experience and we have a lot more documentation for it.