GET http://localhost:3000/api/house-details/[object%20Object]602ac5039b39c90015b3dc44 400(错误请求)

GET http://localhost:3000/api/house-details/[object%20Object]602ac5039b39c90015b3dc44 400 (Bad Request)

在我的 mern 应用程序中,当我尝试更新我的应用程序中的房屋信息时,我收到了这个 400 错误请求。 url 在 id 旁边显示 [object%20Object] 这个我认为是来自更新函数的 result,但我不知道是什么导致了这个错误。该请求在后端工作,我一直在使用 Postman 测试我所有的路线,它们都成功了。我也收到此错误 0.chunk.js:7824 Uncaught (in promise) Error: Request failed with status code 400 at createError (0.chunk.js:7824) 我怀疑这可能与我尝试更新 updateHouse 函数中的数据的方式有关。

组件编辑表单

import React, { useState, useEffect } from "react";

// import axios from "axios";

import axios, {get, put}  from 'axios'

import { Link, withRouter } from 'react-router-dom'

const EditHouseForm = (props) => {

    // const initialState = { 
   
    //     price: 0,
    //      city: '',
    //      county: '',
    //      numOfBeds: 0,
    //      numOfBaths: 0,
    //      numOfGarages: 0,
    //      isSaleOrRent: '',
    //      us_state: '',
    //      sqaurefeet: 0,
    //      house_image: 0,
       
    //    }

    //    const [house, setHouse] = useState(initialState)
  const [house, setHouse] = useState({ 
   id: '',
   price: 0,
    city: '',
    county: '',
    numOfBeds: 0,
    numOfBaths: 0,
    numOfGarages: 0,
    isSaleOrRent: '',
    us_state: '',
    sqaurefeet: 0,
    house_image: 0,
  
  });

const [houseShow, setShowLoading] = useState(true);

  const url = `http://localhost:5000/api/house-details/edit/${props.match.params.id}`;

  useEffect(function() { 
      setShowLoading(false);
      const fetchData = async () =>{
            const result = await axios(`/api/house-details/${props.match.params.id}`);
            setHouse(result.data);
            console.log(result.data)
            setShowLoading(false)
      };
      fetchData()
  }, [])
  
//   useEffect(function() {
//     async function getHouse() {
//       try {
//         const response = await axios.get(url);
//         setHouse(response.data);        
//       } catch(error) {
//         console.log(error);
//       }
//     }
//     getHouse();    
//   }, [props,url]);




  const updateHouse = (e) =>{
      setShowLoading(true);
      e.preventDefault();
      const data ={ 
        price: house.price,
        city: house.city,
        county: house.county,
        numOfBeds: house.numOfBeds,
        numOfBaths: house.numOfBaths,
        numOfGarages: house.numOfGarages,
        isSaleOrRent: house.isSaleOrRent,
        us_state: house.us_state,
        sqaurefeet: house.sqaurefeet,
        house_image: house.house_image
      };
      put(`/api/house-details/edit/${props.match.params.id}`, data).then((result)=>{
          setShowLoading(false)
          props.history.push(`/house-details/${result + props.match.params.id}`)
      }).catch((error)=>{
          setShowLoading(false)
        console.log(error)
      })
  }

  const onChange = (e) =>{
      e.persist();
      setHouse({...house, [ e.target.name]: e.target.value})
  }

  return (
    <div>
      <h1>hello world</h1>
      <form className="form" onSubmit={updateHouse}>
      <label> House Price</label>
                <input type="number" placeholder="House Price" 
                onChange={onChange} defaultValue={house.price  || undefined }
                />
                <label >County</label>
              <input type="text" placeholder="County" 
              onChange={onChange}  defaultValue={house.county || ''}/>
               
                <label >House Location(City)</label>
                <input type="text" placeholder="City" 
                onChange={onChange} defaultValue={house.city || ''}
                />
                <label>House Location(State)</label>
                <input type="text" placeholder="State"
                onChange={onChange} defaultValue={house.us_state || '' }
                />
                <label>Sale or Rent</label>
                <select onChange={onChange} defaultValue={house.isSaleOrRent || '' }>
                    <option>...</option>
                    <option value={`SALE`}>Sale</option>
                    <option value={`RENT`}>Rent</option>
                </select>
                <label >Sqft</label>
               <input type="number" placeholder="sqft"
               onChange={onChange} defaultValue={house.squarefeet || undefined }
               />
                <label > Number of bedrooms</label>
                <input type="number" placeholder="Number of bedrooms" 
                onChange={onChange} defaultValue={house.numOfBeds || undefined  }
                />
                <label> Number of bathrooms</label>
                <input type="number" placeholder="Number of bathrooms" 
                onChange={onratechange} defaultValue={house.numOfBaths || undefined }
                />

            
                <label > Number of garages</label>
                <input type="number" placeholder="Number of garages" 
                onChange={onChange} defaultValue={house.numOfGarages || undefined}
                />
                 <label>House image</label>
                <input type="file" placeholder="house image" 
                onChange={onChange} 
                />

              <button className="button" type="submit">Update</button>
      </form>
       
    </div>
  );
};

export default withRouter(EditHouseForm);

后端


router.put('/api/house-details/edit/:id', (req, res)=>{

    House.findByIdAndUpdate(req.params.id, req.body).then(()=>{
            res.status(200).end()
    
    })
})

``


  [1]: https://i.stack.imgur.com/OWPM4.png

由于 result 是一个对象,而您正试图将它与字符串连接,JS 将对象强制转换为字符串 => '[object Object]'.

在 URL (/api/house-details/[object%20Object]602ac5039b39c90015b3dc44) 中尝试获取 ID 格式错误的房屋详细信息时,您似乎得到了 400 Bad request

props.history.push(`/house-details/${result + props.match.params.id}`)

应该是

props.history.push(`/house-details/${props.match.params.id}`)