javascript - 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;
解决方案
我通过控制台记录错误响应数据发现了问题。它返回了消息
“没有此用户的个人资料”
这意味着我使用的用户与我在 Postman 中使用的用户不同。
推荐阅读
- javascript - 位于 javascript 文件中的 HTML DOM 中的 onClick 事件调用生成错误的 javascript 函数
- javascript - Javascript ES6计算对象数组的总和
- lambda - 如何在 Java 8 中替换以下代码
- syntax-error - 将数组移动 k 的函数中的语法错误
- javascript - 更改函数中参数的默认值,可以吗?
- bash - 如何过滤期望脚本中命令的输出
- ios - 旋转设备时如何更改 SKScene 大小?
- assembly - 显示模数余数
- javascript - 如何模拟输入框上的点击事件
- php - 有人了解.rain 吗?显示第 4 层类别页面