Fetch error - Missing \"data\" payload in the request body

The GraphQL and Strapi API are changed and they added a parent level to the json object where the entire JSON object that has to be fetch must have a parent key called data, if you submit the request without this key, the API is rejected with a 400 error.

My JSON I submit is like this

{"title": "aaa", "rating": "3", "body": "aa", "categories": "5"}

The api requires it to be like this

{"data" : {"title": "aaa", "rating": "3", "body": "aa", "categories": "5"}}

How can I tweak my code in order to insert a parent key in this JSON object?

With Postman I am able to post the data in the Strapi, by submiting the data like this:

{ "data": {
    "title": "the best car",
    "rating": 7,
    "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt. ",
    "categories": [3,7,4]

    }
}

My full code is bellow:

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery, gql } from '@apollo/client'
import { useParams, Link } from 'react-router-dom'

const CATEGORIES = gql`
  query GetCategories {
    categories{
      data
      {
        id
        attributes{
          name
        }
      }
    }
  }
`

const token ="AlaBala"
const Create = () => {
    const [title, setTitle] = useState('');
    const [body, setBody] = useState('');
    const [rating, setRating] = useState(3);
    const [categories, setCategories] = useState(5);
    const history = useNavigate();

    const { loading, error, data } = useQuery(CATEGORIES)

    if (loading) return <p>Loading categories...</p>
    if (error) return <p>`Error! ${error}`</p>

    const handleSubmit = (e) => {
        e.preventDefault();
        const review = { title, rating, body, categories };
        console.log(review)

        fetch('http://localhost:1337/api/reviews/', {
            method: 'POST',
            mode: 'cors',
            headers: { "Content-Type": "application/json",
                "Authorization" : "Token " + token },
            body: JSON.stringify(review)

        })
    }
return (object etc...)


Solution 1:

Try to change your fetch call to this, pay attention to the body field:

fetch('http://localhost:1337/api/reviews/', {
            method: 'POST',
            mode: 'cors',
            headers: { "Content-Type": "application/json",
                "Authorization" : "Token " + token },
            body: JSON.stringify({data:review})

        })