首页 > 解决方案 > Axios GET Request 在 Postman 中工作但抛出 400 错误 - Redux

问题描述

我正在完成一个完整的堆栈项目。到目前为止,我已经创建了一个登录和注册,它们都可以工作并且它们返回一个 jwt Web 令牌。我正在尝试向 (/api/profile/me) 发出 GET 请求以获取登录的用户配置文件,但出现 400 错误。它在邮递员中工作,但反应失败。

在此处输入图像描述

动作 - profile.js

import axios from 'axios';

import { GET_PROFILE, PROFILE_ERROR } from './types';

// Get current users profile
export const getCurrentProfile = () => {
  return async (dispatch) => {
    try {
      const res = await axios.get('/api/profile/me');

      dispatch({
        type: GET_PROFILE,
        payload: res.data,
      });
    } catch (error) {
      dispatch({
        type: PROFILE_ERROR,
        payload: {
          msg: error.response.statusText,
          status: error.response.status,
        },
      });
    }
  };
};

减速器 - profile.js

import { PROFILE_ERROR, GET_PROFILE } from '../actions/types';

const initialState = {
  profile: null,
  profiles: [],
  repos: [],
  loading: true,
  error: {},
};

export default function (state = initialState, action) {
  const { type, payload } = action;

  switch (type) {
    case GET_PROFILE:
      return {
        ...state,
        profile: payload,
        loading: false,
      };
    case PROFILE_ERROR:
      return {
        ...state,
        error: payload,
        loading: false,
      };
    default:
      return state;
  }
}

我要加载操作的仪表板

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useSelector, useDispatch } from 'react-redux';
import { getCurrentProfile } from '../../actions/profile';
const Dashboard = () => {
  const auth = useSelector((state) => state.auth);
  const profile = useSelector((state) => state.profile);

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getCurrentProfile());
  }, []);
  return (
    <div className="container">
      <p className="dashboard-heading">Dashboard</p>
    </div>
  );
};

export default Dashboard;

标签: javascriptnode.jsreactjsreduxreact-redux

解决方案


我通过控制台记录错误响应数据发现了问题。它返回了消息

“没有此用户的个人资料”

这意味着我使用的用户与我在 Postman 中使用的用户不同。


推荐阅读