首页 > 解决方案 > react 和 redux 以及 axios 中的请求失败,状态码为 404

问题描述

我很困惑为什么会这样。它说“属性'posts'在类型'DefaultRootState'.ts(2339)上不存在”,即使在组合减速器中帖子在那里。 like so.

import React from 'react';
import {  useSelector } from 'react-redux';
import Post from './Post/Post';

import useStyle from './Styles'
const Posts = () =>
{
    const posts = useSelector((state) => state.posts);// the error is shown here. 
    const classes = useStyle();
    console.log(posts);
    console.log();
    return (
        <>
        <h1>POSTS</h1>
        <Post/>
        <Post/>
        </>
    )
};

export default Posts;

当我运行程序时,它显示 这是我尝试创建帖子的时候

这是我的 combineReducers。我的州也发帖。

export default (posts = [] , action) =>{
switch(action.type)
{
    case 'FETCH_ALL':
       return action.payload;
    case 'CREATE':
        return [...posts, action.payload];
    default:
        return posts;
     }
   };

我在 combineReducers 中发表过帖子。

    import { combineReducers } from "redux";

    import posts from './posts'


    export default combineReducers ({ posts })

这些是已定义的操作。

    import * as api from '../api';

    export const getPosts = () => async (dispatch) =>{
  try {
        const { data } = await api.fetchPosts();
        dispatch({type:'FETCH_ALL' , payload : data});
    } catch (error) {
        console.log(error.message);
    }
}

export const createPost = (post) => async (dispatch) => {
    try {
          const { data } = await api.createPost(post);
          dispatch({type:'CREATE' , payload: data})
    } catch (error) {
        console.log(error.message);
    }
}

   

标签: reactjsreduxaxioshttp-status-code-404mern

解决方案


这并不是告诉您 React 或 Redux 中的错误,而是告诉您在您的服务器上,没有http://localhost:5000/posts可以使用 POST 请求访问的端点。

要么你有一个错误的 url,要么你必须检查你的服务器实现。


推荐阅读