如何解决React + Redux中的错误400?

hsvhsicv  于 2023-02-12  发布在  React
关注(0)|答案(1)|浏览(185)

对每个人来说,我有一个关于请求服务器的问题。我得到错误400,但我不明白问题在哪里,我检查了我的代码一千次,它看起来像所有的好。基本上,与此请求我得到的"订单号"。
这是减速器:

const initialState = {
  status: "STALE",
};

export const orderObjectReducer = (state = initialState, action) => {
  if (action.type === "SEND_ORDER_FAILED") {
    return { status: "FAILED" };
  }
  if (action.type === "SEND_ORDER_IS_LOADING") {
    return {
      status: "LOADING",
    };
  }
  if (action.type === "SEND_ORDER_STALE") {
    return {
      status: "STALE",
    };
  }
  if (action.type === "SEND_ORDER_SUCCESS") {
    return {
      status: "SUCCESS",
      data: action.payload,
    };
  }
  return state;
};

export const makeOrder = (ingredientsIds) => async (dispatch) => {
  dispatch({
    type: "SEND_ORDER_IS_LOADING",
  });

  const result = await fetch("https://norma.nomoreparties.space/api/orders", {
    method: "POST",
    body: JSON.stringify({ ingredients: ingredientsIds }),
  })
    .then((res) => res.json())
    .catch(() => null);

  if (!result || !result.success) {
    dispatch({
      type: "SEND_ORDER_FAILED",
    });
    return result;
  }
  dispatch({
    type: "SEND_ORDER_SUCCESS",
    payload: result,
  });
};

触发请求的按钮:

<Button
      disabled={selectedIngredientsIds.length === 0}
      htmlType="button"
      onClick={() => dispatch(makeOrder(selectedIngredientsIds))}
      type="primary"
      size="large"
      extraClass="mr-4" >
      Оформить заказ
    </Button>

这是获取请求结果的组件:

export const OrderDetails = () => {
  const { status, data } = useAppSelector((store) => store.orderObject);

  const dispatch = useAppDispatch();
  if (status === "STALE" || status === "LOADING") {
    return null;
  }

  return (
    <Modal onClose={() => dispatch({ type: "SEND_ORDER_STALE" })}>
       {status === "FAILED" ? ("Ошибка") : (
        <>
          <p className={`${orderDetailsStyle.orderDetails__orderNumber} text text_type_digits-large mt-30 mb-8`}>{data?.order.number}</p>
          <p className="text text_type_main-medium mb-15">идентификатор заказа</p>
          <img src={done} alt="заказано" className={orderDetailsStyle.orderDetails__image}/>
          <p className="text text_type_main-default mb-2">Ваш заказ начали готовить</p>
          <p className="text text_type_main-default text_color_inactive mb-30">Дождитесь готовности на орбитальной станции</p>
        </>
      )}
    </Modal>
  );
};

我怎样才能解决这个问题呢?

hfwmuf9z

hfwmuf9z1#

一个400 Bad Request仅仅意味着请求是坏的。服务器说你发送的东西有问题。
为了在应用之外测试这一点,我在Firefox中使用了一个名为RESTED Client的免费扩展来测试POST到您的URL(https://norma.nomoreparties.space/api/orders),并使用{ ingredients: ["1", "2"]}的伪主体。

{
  "success": false,
  "message": "Ingredient ids must be provided"
}

问题出在你发送的数据上。我之所以知道这一点,是因为我准确地重复了你的应用在这里所做的事情:

const result = await fetch("https://norma.nomoreparties.space/api/orders", {
  method: "POST",
  body: JSON.stringify({ ingredients: ingredientsIds }),
})

相关问题