函数找不到用户时Axios响应未定义



我试图从express服务器访问错误消息与redux工具包。如果没有找到用户,则发送带有状态码的错误消息。一切都是好的,当我使用邮差,我得到错误响应。但是当我试图访问这个客户端,axios的响应是未定义的,当我得到错误。在网络选项卡中,我仍然得到错误。这将导致redux toolkit reducer不拒绝,并且我无法获得错误消息。

服务器控制器及业务功能

controller
....
try {

const user = await findUser({
...some values
});
//I want this message in redux error message
if (!user) return res.status(404).send('No user found!') 

const response = await friendService.sendInvitation({...some values});

res.send(response);
} catch (error) {
res.status(400).send(error);
}
...
const findUser=async({id,username})=>{

const user= await users.findOne(...some logic)


return user
}

findUser返回用户如果找到,如果没有,则未定义。当我使用axios并寻找不存在的用户时,我得到未定义的响应。但是我不能从后台得到任何错误。

编辑
findUser返回null如果没有找到用户
Redux工具箱切片调用api

const api = axios.create({
baseURL:'http://localhost:4000/api',
headers:{
'Content-Type':"application/json"
},
withCredentials:true
})
....
const sendInvitation = createAsyncThunk("friends/sendInvitation", async({ username, shortId }, thunkApi) => {
try {
if (!username || !shortId) return;
const response = await api.post(`/friend/send`, { username, shortId })
return response;
} catch (error) {
console.log(error)
}
const sendInvitation = createAsyncThunk("friends/sendInvitation", async({ username, shortId }, thunkApi) => {
try {
if (!username || !shortId) return;
const {data} = await api.post(`/friend/send`, { username, shortId })
return data;
} catch (error) {
const message =
(error.response && error.response.data && error.response.data.message) || error.message || error.toString();
return thunkAPI.rejectWithValue(message);
}

使用您的extraReducer,

.addCase(sendInvitation.rejected, (state, action) => {
state.isLoading = false;
state.isError = true;
state.message = action.payload;
})

所以当请求失败时,您在状态中发送一条消息,这是通过拒绝调用

实现的我假设你有一个像这样的初始状态

const initialState = {
data: null,
isError: false,
isSuccess: false,
isLoading: false,
message: "",
};
if (!user) return res.status(404).send({message:'No user found!'}) 

最新更新