Axios GET 请求在 Postman 中有效,但抛出 400 错误 - Redux

Axios GET Request works in Postman but throws 400 error - Redux

提问人:Ope Afolabi 提问时间:11/15/2021 更新时间:11/15/2021 访问量:293

问:

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

enter image description here

操作 - 配置文件 .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,
        },
      });
    }
  };
};

reducers - 配置文件.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;
javascript node.js reactjs react-redux

评论

0赞 MMH 11/15/2021
您的前端和后端应用是否在同一端口“5000”上运行?
0赞 Ope Afolabi 11/15/2021
是的,它们在同一端口上运行

答:

0赞 Ope Afolabi 11/15/2021 #1

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

“此用户没有配置文件”

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