400 错误请求的 CreateAsyncThunk 问题

CreateAsyncThunk Problem with 400 Bad request

我已经创建了一个asyncthunk,但是状态码是400的时候,request的结果还是fulfilled,用createasyncthunk和fetch处理400错误的方法是什么api?

这是一个操作代码:

    import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import authService from "./auth-service";


// Get user from localStorage
const user = JSON.parse(localStorage.getItem("user"));

const initialState = {
  user: user ? user : "",
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

// Register user
export const register = createAsyncThunk(
  "auth/signup",
  async (user, thunkAPI) => {
    try {
      return await authService.register(user);
    } catch (error) {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message ||
        error.toString();
      return thunkAPI.rejectWithValue(message);
    }
  }
);

// Login user
export const login = createAsyncThunk("auth/login", async (user, thunkAPI) => {
  try {
    return await authService.login(user);
  } catch (error) {
    const message =
      (error.response && error.response.data && error.response.data.message) ||
      error.message ||
      error.toString();
    return thunkAPI.rejectWithValue(message);
  }
});

export const logout = createAsyncThunk("auth/logout", async () => {
  await authService.logout();
});

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    reset: (state) => {
      state.isLoading = false;
      state.isSuccess = false;
      state.isError = false;
      state.message = "";
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(register.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(register.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.isSuccess = false;
        state.user = "";
      })
      .addCase(register.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isError = false;
        state.isSuccess = true;
        state.message = action.payload;
      })
      .addCase(login.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(login.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.user = action.payload;
      })
      .addCase(login.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
        state.user = "";
      })
      .addCase(logout.fulfilled, (state) => {
        state.user = "";
      });
  },
});

export const { reset } = authSlice.actions;
export default authSlice.reducer;

这是一个服务代码:

import React from 'react'
import Cookies from 'js-cookie'
const API_URL = "http://localhost:5000/api/auth/";


const token = Cookies.get('XSRF-Token')

// Register user
const register = async (userData) => {
  const response = await fetch(API_URL + "signup", {
    method: "POST",
    credentials: 'include',
    headers: {
      'X-CSRF-Token': token,
      'Accept': "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(userData),
  });

  const responseData = await response.json();

  if (response.ok) {
    localStorage.setItem("user", JSON.stringify(responseData));
    return responseData;
  }
};

// Login user
const login = async (userData) => {
  const response = await fetch(API_URL + "login", {
    method: "POST",
    credentials: 'include',
    body: JSON.stringify(userData),
    headers: {
      'X-CSRF-Token': token,
      'Accept': "application/json",
      "Content-Type": "application/json",
    },
  });

  const responseData = await response.json();

  if (response.ok) {
    localStorage.setItem("user", JSON.stringify(responseData));
    return responseData;
  }
};

// Logout user
const logout = () => {
  localStorage.removeItem("user");
};

const authService = {
  register,
  logout,
  login,
};

export default authService;

问题是注册和登录操作,return 即使 post 请求的代码是 400 并且我的意图是发送有关错误的消息

也已完成

如果 response.ok 不为真,您的代码将不会执行任何操作。这就是当您获得 4xx 状态时会发生的情况。

因此,例如,在这段代码中:

// Register user
const register = async (userData) => {
  const response = await fetch(API_URL + "signup", {
    method: "POST",
    credentials: 'include',
    headers: {
      'X-CSRF-Token': token,
      'Accept': "application/json",
      "Content-Type": "application/json",
    },
    // body: JSON.stringify(userData),
  });

  const responseData = await response.json();

  if (response.ok) {
    localStorage.setItem("user", JSON.stringify(responseData));
    return responseData;
  }
};

如果 response.ok 不为真,您只需允许 async 函数具有 undefined return 值。这将解决承诺,具有 undefined 已解决的价值。

也许,您想像这样将任何非 2xx 状态变成拒绝:

// Register user
const register = async (userData) => {
  const response = await fetch(API_URL + "signup", {
    method: "POST",
    credentials: 'include',
    headers: {
      'X-CSRF-Token': token,
      'Accept': "application/json",
      "Content-Type": "application/json",
    },
    // body: JSON.stringify(userData),
  });

  if (response.ok) {
    const responseData = await response.json();
    localStorage.setItem("user", JSON.stringify(responseData));
  } else {
    // reject the promise
    throw new Error(`status code ${response.status}`)
  }

  
};

您可能希望对 fetch().

的所有用途执行类似的操作

因为我发现我希望这是发出请求时的标准行为,所以我有自己的 fetchWrapper() 函数可以自动将任何非 2xx 状态转换为承诺拒绝,因此我不必将其编码到 fetch().

的每次使用中

这里有一个 fetchWrapper 函数的例子,它将任何不在 200-299 范围内的 http 状态变成一个被拒绝的承诺:

async function fetchJSON(url, options) {
    let response = await fetch(url, options);
    if (!response.ok) {
        throw new Error(`status code ${response.status}`);
    }
    return response.json();
}