简体   繁体   English

Axios GET 请求在 Postman 中工作但抛出 400 错误 - Redux

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

I am working through a full stack project.我正在完成一个完整的堆栈项目。 So far, I have created a login and register which both work and they return a jwt web token.到目前为止,我已经创建了一个登录和注册,它们都可以工作并且它们返回一个 jwt Web 令牌。 I am trying to make a GET request to (/api/profile/me) to get the logged in user profile but I get a 400 error.我正在尝试向 (/api/profile/me) 发出 GET 请求以获取登录的用户配置文件,但出现 400 错误。 It works in Postman but fails in react.它在 Postman 中有效,但没有反应。

在此处输入图片说明

actions - profile.js动作 - 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,
        },
      });
    }
  };
};

reducers - profile.js减速器 - 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;
  }
}

Dashboard where I want to load the action我要加载操作的仪表板

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;

I found out the issue by console logging the error response data.我通过控制台记录错误响应数据发现了这个问题。 It returned the message它返回了消息

"There is no profile for this user" “没有该用户的个人资料”

meaning that I used a different user than the one I used in Postman.这意味着我使用的用户与我在 Postman 中使用的用户不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM