开发者问题收集

使用React,Redux和Express从MongoDB删除项目

2020-11-19
1383

我尝试使用 React、Redux 和 Express/Node 从我的 MongoDB 数据库中删除订单行,但我的控制台中出现以下错误:

VM118:1 DELETE http://localhost:3000/api/meals/:id/jp4PaZve3 404 (Not Found) 

我不确定为什么它指向端口 3000,而我的本地服务器正在 5000 上运行?

在我的服务器文件中,我在 Express 中创建了以下删除端点

app.delete("/api/meals/:id", async (req, res) => {
  const deletedMeal = await Meal.findByIdAndDelete(req.params.id);
  res.send(deletedMeal);
});

在我的 redux 操作中,我有以下内容(我不确定这是否正确):

export const deleteMeal = (id) => async (dispatch) => {
  await fetch("/api/meals/:id/" + id, {
    method: "DELETE",
  });
  dispatch({
    type: DELETE_MEAL,
    payload: id,
  });
};

我的 UpdateMenu 屏幕如下:

import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchMeals, deleteMeal } from "../actions/mealActions";

class UpdateMenuScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meal: null,
    };
  }

  componentDidMount() {
    this.props.fetchMeals();
  }

  deleteMeal(id) {
    this.props.deleteMeal(id);
  }

  render() {
    return (
      <div>
        <h3>Current Menu</h3>
        {!this.props.meals ? (
          <div>Loading...</div>
        ) : (
          <ul className="meals">
            {this.props.meals.map((meal) => (
              <li key={meal._id}>
                <div className="meal">
                  <p>{meal.title}</p>
                  <button
                    className="button"
                    onClick={() => this.props.deleteMeal(meal._id)}
                  >
                    Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
        <button>Add New Menu Item</button>
      </div>
    );
  }
}

export default connect((state) => ({ meals: state.meals.items }), {
  fetchMeals,
  deleteMeal,
})(UpdateMenuScreen);

但是,当我尝试在 Postman 中运行我的删除方法时,它不起作用。有人能看到我做错了什么吗?

1个回答

在您的 deleteMeal 操作中,您必须使用模板字符串将 id 动态地放入 URL 中,

await fetch("/api/meals/:id/" + id

1) it's equal to /api/meals/:id/id but according to your backend it should be /api/meals/:id
2) and you have to put the whole URL like http://localhost:5000/api/meals/${id} cause if you don't put the base, it will do a request on the port of your client so 3000

///////

因此,不要使用:

export const deleteMeal = (id) => async (dispatch) => {
  await fetch("/api/meals/:id/" + id, {
    method: "DELETE",
  });
  dispatch({
    type: DELETE_MEAL,
    payload: id,
  });
};

尝试使用这个:

export const deleteMeal = (id) => async (dispatch) => {
  await fetch(`http://localhost:5000/api/meals/${id}/`, {
    method: "DELETE",
  });
  dispatch({
    type: DELETE_MEAL,
    payload: id,
  });
};
VersifiXion
2020-11-19