React添加电影时出现Bad Request错误,请求协助排查解决
Hey there! Let's figure out why you're getting that Bad Request error when adding a movie. Looking through your code, I spot a couple of key issues that are causing this:
1. Mismatched Data Format Between Frontend and Backend
Your backend uses formidable to parse multipart/form-data (since you're handling file uploads for photos), but your frontend is sending a JSON string via JSON.stringify(values). Formidable can't parse JSON, so it throws a Bad Request.
2. Incorrect name Attributes in Form Inputs
Looking at your AddMovie.js form, several inputs have the wrong name attribute (e.g., the movie_name input has name="photo"). This means even if you sent the right data format, your backend wouldn't pick up the correct field values, triggering the "please include all fields" error.
Fixes Step-by-Step
Update Form Input name Attributes
First, correct the name attributes in your form to match the field names your backend expects:
// In addMovieForm() <div className="form-group"> <input onChange={handleChange("movie_name")} name="movie_name" className="form-control" placeholder="movie_name" value={movie_name} /> </div> <div className="form-group"> <input onChange={handleChange("actor")} name="actor" className="form-control" placeholder="actor" value={actor} /> </div> <!-- Repeat this fix for country_of_origin, duration, and director inputs -->
Use FormData for File + Form Data
Since you're uploading a file, you need to use FormData to package your data correctly. Update your state and handlers:
- Enable and initialize the
formDatastate:
const [values,setValues] = useState({ movie_name:'', actor:'', country_of_origin:'', duration:'', director:'', photo:'', loading:false, error:'', addedMovie:'', getRedirect:false, formData: new FormData() // Initialize FormData here })
- Update
handleChangeto populateformData:
const handleChange = name => event => { const value = name === "photo" ? event.target.files[0] : event.target.value; values.formData.set(name, value); // Add the value to FormData setValues({...values, [name]: value}); };
- Modify
onSubmitto sendformDatainstead of JSON:
const onSubmit = (e) => { e.preventDefault(); setValues({...values, error:'', loading:true}) // Pass the FormData object directly, not JSON-stringified values addMovie(user._id,token,values.formData).then(data =>{ if(data.error){ setValues({...values,error:data.error}) }else{ setValues({ ...values, movie_name:'', actor:'', country_of_origin:'', duration:'', director:'', photo:'', loading:false, addedMovie: data.movie_name }); // Reset FormData for the next submission values.formData = new FormData(); } }) }
Adjust API Call Headers
In adminapicall.js, remove any manual Content-Type header (the browser will automatically set the correct multipart/form-data header with a boundary when you pass a FormData object):
export const addMovie = (userId,token,movie)=>{ return fetch(`${API}/movie/addMovie/${userId}`,{ method : "POST", headers:{ Accept:'application/json', // Keep this to parse the response Authorization: `Bearer ${token}` }, body:movie }).then(response => { return response.json() }) .catch(err => console.log(err)) }
Why This Works
FormDataproperly encapsulates both text fields and the photo file in a formatformidablecan parse.- Correct input
nameattributes ensure your backend receives all required fields, avoiding the "please include all fields" error. - The browser handles the correct content type for file uploads, so your backend can process the request without issues.
内容的提问来源于stack exchange,提问作者user13427179




