Axios的get请求正在返回用户:使用Redux操作调用后端的空值吗?

时间:2019-03-09 12:07:14

标签: node.js reactjs express redux axios

我所有的axios发布请求均正常运行。 邮递员的get请求也可以正常工作,但是当我使用axios发出get请求时,它将从app.get请求的auth中间件返回user:null。

这是我的文件:

user.actions file:-

export function auth() {
    const request = 
    axios.get(`http://localhost:3001${USER_SERVER}/auth`)
        .then(response => response.data)
    return {
        type: AUTH_USER,
        payload: request
    }
}

这是我的服务器文件中的请求:

app.get('/api/users/auth', auth, (req, res) => {
    res.status(200).json({
        isAdmin: req.user.role === 0 ? false : true,
        isAuth: true,
        email: req.user.email,
        name: req.user.name,
        lastname: req.user.lastname,
        role: req.user.role,
        cart: req.user.cart,
        history: req.user.history,
        contactnumber: req.user.contactnumber,
        address: req.user.address
    })
})

这是我的身份验证中间件:-

const { User } = require('../models/user')

let auth = (req, res, next) => {
    let token = req.cookies.x_auth
    User.findByToken(token, (err, user) => {
        if (err)
            throw err
        if (!user)
            return res.json({
                user: user,
                isAuth: false,
                error: true
            })
        console.log(user)
        req.token = token
        req.user = user
        next()
    })
}

module.exports = { auth }

这是我的减速器文件中的减速器:

case AUTH_USER:
            return { ...state, userData: action.payload } 

这是我的auth.js文件,登录后我在其中发出身份验证请求  从浏览器中:

class AuthCheck extends Component {
        state = {
            loading: false
        }

        componentDidMount() {
            this.props.dispatch(auth()).then(Response => {
                console.log(this.props.user)
                let user = this.props.user.userData
                console.log(user)
            })
        }
        render() {
            if (this.state.loading) {
                return (
                    <div className='main_loader'>
                        <Loader size='big' active />
                    </div>
                )
            }
            return (
                <ComposedClass {...this.props} user={this.props.user} />
            )
        }
    }

    function mapStateToProps(state) {
        return {
            user: state.user
        }
    }
    return connect(mapStateToProps)(AuthCheck)
}

auth.js文件中的console.log返回:

{用户:null,isAuth:false,错误:true}

即使在我以注册用户身份登录后,我的loginSuccess = true也是如此。

出什么问题了?

这是我在客户端的index.js文件中创建的存储文件

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, ReduxThunk)(createStore);


ReactDOM.render(
    <Provider store={createStoreWithMiddleware(Reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())}>
        <BrowserRouter>
            <Routes />
        </BrowserRouter>
    </Provider>

    , document.getElementById('root'));

这是我的联合减速机文件:

import { combineReducers } from 'redux'
import user from './user_reducer'

const rootReducer = combineReducers({
    user
})

export default rootReducer

2 个答案:

答案 0 :(得分:0)

代码中的问题是,在化简文件中,您将action.payload设置为userData,但是在组件中,您以state.user身份访问,这是不正确的。应该是state.userData

所以改变

   function mapStateToProps(state) {
       return {
          user: state.user
       }
   }

收件人

  function mapStateToProps(state) {
       return {
           user: state.userData
       }
  }

因此在渲染器内执行console.log(this.props.user);您将获得用户数据

答案 1 :(得分:0)

您可以显示您的CombineReducers和createStore函数吗?此外,您的authAction函数似乎有点不正常。尝试以下方法:

export const auth = () => async dispatch {
    const response = await axios.get(`http://localhost:3001${USER_SERVER}/auth`);            
    dispatch({
        type: AUTH_USER,
        payload: response.data
    })
}

将其包装在try-catch中以处理网络错误。