You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Express、Axios和React实现Delete方法失败问题求助

Fixing Your Express-Axios-React DELETE Method Issue

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:

  • id is a number (not an array), so it doesn't have a splice method
  • splice takes 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/:id route captures the ID from the URL, making it accessible via req.params.id in Express.
  • CORS: The cors middleware handles preflight OPTIONS requests and allows cross-origin communication between your React app and Express server.
  • State Update: Using filter creates a new array (following React's immutable state principles) instead of mutating the original array directly. If you prefer splice, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:05:52