1

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)
  })
})
Charlie Vdb
  • 45
  • 1
  • 9

2 Answers2

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

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • 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 (http://localhost:3001/static/js/0.chunk.js:318:13) at new Promise () at xhrAdapter (http://localhost:3001/static/js/0.chunk.js:301:10) at dispatchRequest (http://localhost:3001/static/js/0.chunk.js:924:10) – Charlie Vdb May 10 '20 at 14:16
  • @CharlieVdb, so your question error is solved, now that is something is react related – Vivek Doshi May 10 '20 at 14:19
  • What is the value of `process.env.REACT_APP_API_BASE` – Vivek Doshi May 10 '20 at 14:22
  • What do you mean? Any idea what the error could be? – Charlie Vdb May 10 '20 at 14:23
  • @CharlieVdb, as long as I know this happens when you are missing `http://` or `https://` in your URL , check that , for ref check this : https://stackoverflow.com/questions/42461174/angular-2-failed-to-execute-open-on-xmlhttprequest-invalid-url – Vivek Doshi May 10 '20 at 14:24
  • thanks man where can I find my URL? I have a .env file in back-end and .env.production & .env.development files in my front-end – Charlie Vdb May 10 '20 at 14:29
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213558/discussion-between-vivek-doshi-and-charlie-vdb). – Vivek Doshi May 10 '20 at 14:29
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

Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
  • 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 (http://localhost:3001/static/js/0.chunk.js:318:13) at new Promise () at xhrAdapter (http://localhost:3001/static/js/0.chunk.js:301:10) at dispatchRequest (http://localhost:3001/static/js/0.chunk.js:924:10) – Charlie Vdb May 10 '20 at 14:19