首页 > 解决方案 > 提交表单时出现 400 错误请求

问题描述

我在提交表单时收到类似 400 bad request 的错误,不知道发生了什么问题,请帮助解决我的错误

此 img 将帮助您捕获错误
https://ibb.co/X8NKGzdhttps://ibb.co/Y8fXsBj

addMovie.js

这是我的前端 addmovie 逻辑

import React,{useState} from 'react';
import Navbar from '../pages/Navbar';
import Footer from '../pages/Footer';
import {Link} from 'react-router-dom';
import {isAuthenticated} from '../Auth/index';
import {addMovie} from '../Admin/adminapicall';

const AddMovie = () => {

  const {user,token} = isAuthenticated();

const [values,setValues] = useState({
    movie_name:'',
    actor:'',
    country_of_origin:'',
    duration:'',
    director:'',
    photo:'',
    loading:false,
    error:'',
    addedMovie:'',
    getRedirect:false,
    // formData:''
})

    const {movie_name,actor,country_of_origin,duration,director,photo,loading,error,addedMovie,getRedirect} = values;

    const handleChange = name => event => {
        const value = name === "photo" ? event.target.files[0] : event.target.value
        // formData.set(name,value); 
        setValues({...values,[name]:value})
    };

    const onSubmit = (e) => {
        e.preventDefault();
        setValues({...values,error:'',loading:true})
        addMovie(user._id,token,JSON.stringify(values)).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
            })
          }
        })
        
    }

    const successMessage = () => (
      <div className='alert alert-success mt-3'
         style={{display : addedMovie ? '' : 'none'}}>
           <h4>{addedMovie} added successfully</h4>
        </div>
    )


    // const successMessage = () => {
      
    // }

    const addMovieForm = () => (
        <form >
          <span>Post photo</span>
          <div className="form-group">
            <label className="btn btn-block btn-success">
              <input
                onChange={handleChange("photo")}
                type="file"
                name="photo"
                accept="image"
                placeholder="choose a file"
              />
            </label>
          </div>
          <div className="form-group">
            <input
              onChange={handleChange("movie_name")}
              name="photo"
              className="form-control"
              placeholder="movie_name"
              value={movie_name}
            />
          </div>
          <div className="form-group">
            <input
              onChange={handleChange("actor")}
              name="photo"
              className="form-control"
              placeholder="actor"
              value={actor}
            />
          </div>
          <div className="form-group">
            <input
              onChange={handleChange("duration")}
              type="number"
              className="form-control"
              placeholder="duration"
              value={duration}
            />
          </div>
          <div className="form-group">
            <input
              onChange={handleChange("country_of_origin")}
              type="text"
              className="form-control"
              placeholder="country_of_origin"
              value={country_of_origin}
            />
          </div>
          <div className="form-group">
            <input
              onChange={handleChange("director")}
              type="text"
              className="form-control"
              placeholder="director"
              value={director}
            />
          </div>
          
          <button type="submit" onClick={onSubmit} className="btn btn-success mb-2">
            Add Movie
          </button>
        </form>
      );
    return (
        <div>
            <Navbar/>
                <div className='container'style={{height:'0px'}}>
              <Link to='/admin/dashboard'> <h1 className=' bg-info text-white p-4 text-decoration-none'>Admin Home</h1> </Link>
              <div className='row bg-dark text-white rounded'>
                    <div className='col-md-8 offset-md-2'>
                      {successMessage()}
                      {addMovieForm()}
                    </div>

                </div> 

                </div>
                
            <Footer/>
        </div>
    )
}

export default AddMovie;

api调用

这是我的 api 请求,前端与后端交谈

import {API} from '../backend';

//add movie
export const addMovie = (userId,token,movie)=>{
    return fetch(`${API}/movie/addMovie/${userId}`,{
        method : "POST",
        headers:{
            Accept:'Application/json',
            "Content-Type" : "application/json",
            Authorization: `Bearer ${token}`
        },
        body:JSON.stringify(movie)
    }).then(response => {
        return response.json()
    })
    .catch(err => console.log(err))
}

//get all movie

export const getAllMovies = () => {
    return fetch(`${API}/movies`,{
        method : "GET"
    })
    .then(response => {
        return response.json();
    })
    .catch(err => console.log(err))
}

//get a movie

export const getMovie = movieId =>{
    return fetch(`${API}/movie/${movieId}`,{
        method : "GET"
    })
    .then(response => {
        return response.json();
    })
    .catch(err => console.log(err))
}

//update movie

export const updateMovie = (movieId,userId,token,movie)=>{
    return fetch(`${API}/movie/${movieId}/${userId}`,{
        method : "PUT",
        headers:{
            Accept:'Application/json',
            Authorization: `Bearer ${token}`
        },
        body:movie
    }).then(response => {
        return response.json()
    })
    .catch(err => console.log(err))
}

//delete movie

export const deleteMovie = (movieId,userId,token)=>{
    return fetch(`${API}/movie/${movieId}/${userId}`,{
        method : "DELETE",
        headers:{
            Accept:'Application/json',
            Authorization: `Bearer ${token}`
        }
    }).then(response => {
        return response.json()
    })
    .catch(err => console.log(err))
}

##后端##

addmovie.js

这是发生错误的后端 addmovie 逻辑

exports.addMovie = (req, res) => {
    let form = new formidable.IncomingForm(); // declare a form
    form.keepExtensions = true;

    form.parse(req, (err, fields, file) => {   //parse the form like err,fields,file
        if (err) {
            return res.status(400).json({
                error: "Problem with image"
            });
        }

        //destructure the field
        const {movie_name,actor,country_of_origin,duration,director } = fields;
        if (!movie_name || !actor || !country_of_origin || !duration || !director) 
        {
            return res.status(400).json({
                error: "please include all fields"
            })
        }

        let movie = new Movie(fields);

        //handle file here
        if (file.photo) {
            if (file.photo.size > 300000) {
                return res.status(400).json({
                    error: "file size to big!"
                })
            }
            movie.photo.data = fs.readFileSync(file.photo.path)
            movie.photo.contentType = file.photo.type;

        }

        //save to the database
        movie.save((err, movie) => {
            if (err) {
                res.status(400).json({
                    error: "saving movie in database failed"
                })
            }
            res.json(movie);
        })
    })
}

标签: node.jsreactjsmongodbreact-hooksreact-router-dom

解决方案


推荐阅读