使用Express、Axios和React实现Delete方法失败问题求助
Hey there, let's walk through the problems in your code and fix them one by one:
1. Mismatched Route Path
Your Express DELETE route is set to /people, but your Axios request is hitting /people/0 (with an ID parameter). Express can't match this path, which is why you're getting the 404 error.
2. Missing CORS Handling
Since your React app and Express server are running on different ports, browsers send an OPTIONS preflight request first. Without CORS configured, this request fails, blocking your DELETE call.
3. Incorrect Logic in React's Remove Function
The line id.splice(name, 1) is invalid:
idis a number (not an array), so it doesn't have asplicemethodsplicetakes an index as the first argument, not a name
Corrected Express Code
First, install the cors package to handle cross-origin requests:
npm install cors
Then update your Express server:
const express = require('express'); const cors = require('cors'); const app = express(); // Allow requests from your React app's origin (adjust port if needed) app.use(cors({ origin: 'http://localhost:3000' })); // Updated DELETE route to accept an ID parameter app.delete('/people/:id', (req, res) => { const personId = req.params.id; // Add your actual data deletion logic here (e.g., from a database/array) console.log(`Attempting to delete person with ID: ${personId}`); res.status(200).send(`Successfully deleted person with ID: ${personId}`); }); app.listen(9000, () => { console.log('Server running on http://127.0.0.1:9000'); });
Corrected React Axios Code
Assuming you have a state holding your people list (like this.state.people), here's the fixed remove function:
remove = (id) => { axios.delete(`http://127.0.0.1:9000/people/${id}`) .then((response) => { // Update state by filtering out the deleted person (immutable update) const updatedPeople = this.state.people.filter(person => person.id !== id); this.setState({ people: updatedPeople }); console.log(response.data); }) .catch((error) => { // Log errors for debugging console.error('Error deleting person:', error); }); }
Key Fixes Explained
- Route Matching: The
/people/:idroute captures the ID from the URL, making it accessible viareq.params.idin Express. - CORS: The
corsmiddleware handles preflight OPTIONS requests and allows cross-origin communication between your React app and Express server. - State Update: Using
filtercreates a new array (following React's immutable state principles) instead of mutating the original array directly. If you prefersplice, you can do this instead:const index = this.state.people.findIndex(person => person.id === id); const updatedPeople = [...this.state.people]; updatedPeople.splice(index, 1); this.setState({ people: updatedPeople });
内容的提问来源于stack exchange,提问作者Jota

