Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

DELETE 400 (BAD REQUEST)

I am trying to create a button that removes through the react app songs that are in a database (MongoDB) and displayed on the screen, this is executed by the server in python, I get the 400 error and i do not know what is the problem since I am new to this.

I have already done the song adding and fetching but the removing does not seem to work it always shows error 400 and says the input is invalid, I tried to change it and fix it multiple ways but since I am a beginner at this I really do not know how to make this work.
here is the server side (python):

@app.route('/remove_song', methods=['DELETE'])
def remove_song():
    data = request.get_json()
    song_id = data.get("songId")
    user_id = data.get("userId")

    if song_id and user_id:
        result = songs_col.delete_one({"_id": ObjectId(song_id), "userId": user_id})
        if result.deleted_count == 1:
            return jsonify({"message": "Song removed successfully"})
        else:
            return jsonify({"message": "Song not found"}), 404
    else:
        return jsonify({"message": "Invalid input"}), 400

here is the client side:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const FetchSongs = ({ userId }) => {
  let user = getUser();
  const [songs, setSongs] = useState([]);
  const removeSong = (songId) => {
    axios.delete('http://localhost:5000/remove_song', { data: { songId, userId: user.email } })
      .then((res) => {
        console.log(res.data);
        if (res.data.message === "Song removed successfully") {
          alert("Song removed from history successfully");
          // Optionally update the state to remove the song from the list
          setSongs(songs.filter(song => song._id !== songId));
        }
      })
      .catch((err) => {
        console.log(err);
        alert("Failed to remove song from history");
      });
  };
  useEffect(() => {
    const fetchSongs = () => {
      axios.get(`http://localhost:5000/songs/${userId}`)
        .then((res) => {
          setSongs(res.data);
        })
        .catch((err) => {
          console.log(err);
        });
    };

    fetchSongs();
  }, [userId]);

  return (
    <div>
      <div style={{border:"#0F52BD solid 2px",width:"800px",display:"flex",flexDirection:"column", gap:"5px",marginLeft:"20%"}}>
        {songs.map(song => (
          <div style={{border:"#0F52BD solid 2px",width:"600px",marginLeft:"13%"}} key={song.id}>
            <h4 style={{fontFamily:"Bahnschrift SemiBold"}}>🎵 {song.songName}</h4> 
            <audio src={song.filePath} controls /> 
            <input  type="button" value="⬇️" style={{backgroundColor:"rgb(220, 230, 250)",border:"solid rgb(220, 230, 250) 2px",fontSize:"40px",cursor: "pointer"}} ></input>
            <input  type="button" value="✖️" style={{backgroundColor:"rgb(220, 230, 250)",border:"solid rgb(220, 230, 250) 2px",fontSize:"40px",cursor: "pointer"}}
             onClick={() => removeSong(song._id)}></input>
            </div>
        ))}
      </div>
    </div>
  );
};

export default FetchSongs;

Tell me if there is a need to clear or add something in the question and thanks for helping!

>Solution :

Common Issues to Check
Headers: Make sure to set the Content-Type to application/json in your Axios request.
Key Names: Ensure the keys in your request data match exactly what your server expects (songId and userId).
Error Messages: If you still receive a 400 error, inspect the error message to determine if there are additional clues.
Additional Debugging Tips
Print Debug Statements: Add print statements in your Flask route to debug the data being received.
Postman: Use Postman or another API testing tool to manually test the endpoint with different payloads to isolate whether the issue is client-side or server-side.
By following these adjustments and checks, you should be able to identify and resolve the issue with the 400 error on your delete request.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading