尝试让我的删除按钮在 REACT 中工作
2020-05-10
200
有人能在我的代码中找出错误吗?我正在尝试使删除按钮工作,删除已单击的特定挑战。
控制台中的错误:
xhr.js:178 DELETE http://localhost:3000/allchallenges/5eb4398f2650390017030bcf 404 (未找到)
具有删除按钮的前端组件
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
我的 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个回答
xhr.js:178 DELETE http://localhost:3000/allchallenges/5eb4398f2650390017030bcf 404 (Not Found)
404:未找到 - 错误明确指出该路径的 api 不存在
因此,您的快速 API 路由存在问题:
将其更改为:
router.delete("/allchallenges",
至:
router.delete("/allchallenges/:id",
NOTE : You can access the params with
req.params
Vivek Doshi
2020-05-10
也许您需要添加路由参数。
router.delete("/allchallenges/:id", (req,res) => {
Challenge
.find()
.then(response => {
res.json(response)
})
.catch(error => {
res.json(error)
})
})
Józef Podlecki
2020-05-10