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
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
try changing
data
, to{ data }
inconst response = await ...
the strapi expects to have keydata
inbody
, when you do it like you did, the body would be equal to data and that is incorrectThe 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?