skip to Main Content

I have a form component that is supposed to create entries in my Reviews content type in strapi. I believe the data is sufficient but i am still getting a 400 bad request error. Here is my component:

import  { useState } from 'react'
import axios from 'axios'
import { FaStar } from 'react-icons/fa'
import style from "./Form.module.css"
import { userData } from "../../Helpers"
import { toast } from 'react-toastify'

const ReviewForm = ({tourTitle}) => {
  const [rating, setRating] = useState('')
  const [body, setBody] = useState('')
  const { accessToken, username } = userData()
  

  const handleSubmit = async (e) => {
    e.preventDefault()

    const data = {
      tour: tourTitle,
      rating,
      body,
      author: username
    };

    try {
      const response = await axios.post('http://localhost:1337/api/reviews',
       data,
       {
        headers: {
          Authorization: `Bearer ${accessToken}`,
          'Content-Type': 'application/json',
        },
      })

      console.log(data)
      toast('Review created successfully!')
      setRating('')
      setBody('')

    } catch (error) {
      console.log(data)
      console.error('Error creating review:', error)
      toast('Error creating review. Please try again.')

    }

  };

  const handleStarClick = (starRating) => {
    setRating(starRating);
  };

  const renderStars = () => {
    const stars = [];
    for (let i = 1; i <= 5; i++) {
      const starClassName = i <= rating ? style.selected : style.star;
      stars.push(
        <FaStar
          key={i}
          className={starClassName}
          onClick={() => handleStarClick(i)}
        />
      );
    }
    return stars;
  };

  return (
    <form onSubmit={handleSubmit} className={style.writeReview}>
      <h2>Write a review:</h2>
      <div className={style.rating}>{renderStars()}</div>

      <div className={style.fieldConatiner}>
            <textarea
                id="body"
                name="body"
                rows="4"
                cols="50"
                value={body}
                onChange={(e) => setBody(e.target.value)}
                required
            />
      </div>  
      
      <button type="submit" className={style.submitBtn}>Submit Review</button>
    </form>
  );
};

export default ReviewForm;

And screenshots of my content type:
Table View of content type
Screen shot of back end new entry

Screenshot of the console showing the error message and the data i am trying to post to my content type

console screenshot

Any help would be very much appreciated I’m loosing it

Ihave tried using the userid, username, tour id and tour title in different combinations and none of them worked.

2

Answers


  1. try changing data, to { data } in const response = await ... the strapi expects to have key data in body, when you do it like you did, the body would be equal to data and that is incorrect

     const response = await axios.post('http://localhost:1337/api/reviews',
           { data }, // << right here
           {
            headers: {
              Authorization: `Bearer ${accessToken}`,
              'Content-Type': 'application/json',
            },
          })
    
    Login or Signup to reply.
  2. The BAD REQUEST error occurs when the server does not understand the data sent with the body.. Please check if these field names are same as per in the backend. Like how are you handling the requests in the backend? And what about the body field in the data object?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search