2

Can someone find the bug in my code? I'm trying to make a delete button work that delete a specific challenge that has been clicked.

The error in the console:

xhr.js:178 DELETE http://localhost:3000/allchallenges/5eb4398f2650390017030bcf 404 (Not Found)


Front-end component that has a delete button

import React from 'react'
import DefaultLayout from "../layout/Default"
import Challengebox from '../components/Challengebox'
import axios from "axios";

class Allchallenges extends React.Component {
    constructor() {
        super()

        this.state = {
           challenges: []
        }

        this.onDelete=this.onDelete.bind(this)
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: `${process.env.REACT_APP_API_BASE}/allchallenges`,
            withCredentials: true
        })
        .then(response => {
            console.log(response)
            let challengeslist = response.data;
            this.setState({challenges: challengeslist})
        })
        .catch(error => {
            console.log("You've made an error charles: ",error)
        })
    }

    onDelete(challengeId){
        axios
        .delete(`${process.env.REACT_APP_API_BASE}/allchallenges/${challengeId}`)
        .then(response => {
            this.props.history.push("/allchallenges")
        })
        .catch(err => console.log(err))
    }

    render() {
        return (
            <DefaultLayout>
                <div className="challengeoverviewlist">
                    <h1>All challenges</h1>   

                    <div className="challengeboxes">

                    {    
                    this.state.challenges.map(challenge => 
                        (
                            <div className="totalbox" key={challenge._id}>

                                <Challengebox 
                                    key={challenge._id} 
                                    id={challenge._id} 
                                    title={challenge.title} 
                                    description={challenge.description}
                                />

                                <button onClick={() => this.onDelete(challenge._id)}>
                                    Delete
                                </button>

                            </div>
                        ))                                                                      
                    }

                    </div>

                </div>    
            </DefaultLayout>
        )
    }
}

export default Allchallenges

My api:

//request challenges
router.get("/allchallenges", (req,res) => {
  Challenge
  .find()
  .then(response => {
    res.json(response)
  })
  .catch(error => {
    res.json(error)
  })
})

//delete challenge
router.delete("/allchallenges", (req,res) => {
  Challenge
  .find()
  .then(response => {
    res.json(response)
  })
  .catch(error => {
    res.json(error)
  })
})

2 Answers 2

1

xhr.js:178 DELETE http://localhost:3000/allchallenges/5eb4398f2650390017030bcf 404 (Not Found)

404 : not found - Error clearly state that the api with that path not exists

So, the issue with your express API routing :

Change this:

router.delete("/allchallenges",

To:

router.delete("/allchallenges/:id",

NOTE : You can access the params with req.params

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks I changed it. This is the error I get now: Uncaught (in promise) DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL at dispatchXhrRequest (localhost:3001/static/js/0.chunk.js:318:13) at new Promise (<anonymous>) at xhrAdapter (localhost:3001/static/js/0.chunk.js:301:10) at dispatchRequest (localhost:3001/static/js/0.chunk.js:924:10)
@CharlieVdb, so your question error is solved, now that is something is react related
What is the value of process.env.REACT_APP_API_BASE
What do you mean? Any idea what the error could be?
@CharlieVdb, as long as I know this happens when you are missing http:// or https:// in your URL , check that , for ref check this : stackoverflow.com/questions/42461174/…
|
0

Perhaps you need to add a route parameter.

router.delete("/allchallenges/:id", (req,res) => {
  Challenge
  .find()
  .then(response => {
    res.json(response)
  })
  .catch(error => {
    res.json(error)
  })
})

Also if you want to delete object and you are using mongoose you have to use Model.findByIdAndDelete

1 Comment

Thanks I added the parameter and changed find() to findByIdAndDelete(), but still get an error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) + Uncaught (in promise) DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL at dispatchXhrRequest (localhost:3001/static/js/0.chunk.js:318:13) at new Promise (<anonymous>) at xhrAdapter (localhost:3001/static/js/0.chunk.js:301:10) at dispatchRequest (localhost:3001/static/js/0.chunk.js:924:10)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.