未处理的拒绝(TypeError):无法读取未定义的属性“令牌”

时间:2019-06-18 10:43:02

标签: javascript reactjs redux typeerror

在提交用于帐户注册(JWT身份验证)的表单后,我收到“令牌”属性的TypeError。 我也在使用React-Redux。

还有,除了存储在localStorage中还有其他方法吗?

下面是身份验证减少程序和操作的代码。

authReducer.js

  modelBuilder.Entity<BookCategory>()
        .HasOne(bc => bc.Book)
        .WithMany(b => b.BookCategories)
        .OnDelete(DeleteBehavior.Restrict);
    modelBuilder.Entity<BookCategory>()
        .HasOne(bc => bc.Category)
        .WithMany(c => c.BookCategories)
        .OnDelete(DeleteBehavior.Restrict);

auth.Actions

import {
    USER_LOADING,
    USER_LOADED,
    AUTH_ERROR,
    REGISTER_SUCCESS,
    REGISTER_FAIL
} from '../actions/types';

const initialState = {
    token: localStorage.getItem('token'),
    isAuthenticated: null,
    isLoading: false,
    user: null
};

export default function (state = initialState, action) {
    switch (action.type) {
        case USER_LOADING:
            return {
                ...state,
                isLoading: true
            };
        case USER_LOADED:
            return {
                ...state,
                isAuthenticated: true,
                isLoading: false,
                user: action.payload
            };
        case LOGIN_SUCCESS:
        case REGISTER_SUCCESS:
            localStorage.setItem('token', action.payload.token);
            return {
                ...state,
                ...action.payload,
                isAuthenticated: true,
                isLoading: false
            };
        case AUTH_ERROR:
        case LOGIN_FAIL:
        case LOGOUT_SUCCESS:
        case REGISTER_FAIL:
            localStorage.removeItem('token');
            return {
                ...state,
                token: null,
                user: null,
                isAuthenticated: false,
                isLoading: false
            };
        default:
            return state;
    }
}

users.js

import axios from 'axios';
import { returnErrors } from './errorActions';
import {
    USER_LOADING,
    USER_LOADED,
    AUTH_ERROR,
    REGISTER_SUCCESS,
    REGISTER_FAIL
} from './types';

//check token and load user
export const loadUser = () => (dispatch, getState) => {
    //User loading
    dispatch({ type: USER_LOADING });

    axios
        .get('/api/auth/user', tokenConfig(getState))
        .then(res =>
            dispatch({
                type: USER_LOADED,
                payload: res.data
            })
        )
        .catch(err => {
            dispatch(returnErrors(err.response.data, err.response.status));
            dispatch({
                type: AUTH_ERROR
            });
        });
};

//register user
export const register = ({ name, email, password }) => dispatch => {
    //headers
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };

    //request body
    const body = JSON.stringify({ name, email, password });

    axios
        .post('api/users', body, config)
        .then(res =>
            dispatch({
                type: REGISTER_SUCCESS,
                payload: res.data
            })
        )
        .catch(err => {
            dispatch(returnErrors(err.response.data, err.response.status, 'REGISTER_FAIL'));
            dispatch({
                type: REGISTER_FAIL
            });
        });
};

//setup config/headers and token
export const tokenConfig = getState => {
    //get token from localstorage
    const token = getState().auth.token;

    //headers
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };

    //if token, add to headers
    if (token) {
        config.headers['x-auth-token'] = token;
    }
    return config;
};

signup.js(组件)

const express = require('express');

const router = express.Router();
const bcrypt = require('bcryptjs');
const config = require('config');
const jwt = require('jsonwebtoken');

//User Model
const User = require('../../models/User');

//@route POST api/users
router.post('/', (req, res) => {
    const { name, email, password } = req.body;

    //validation
    if (!name || !email || !password) {
        return res.status(400).json({ msg: 'Please enter all fields' });
    }

    //check for existing users
    User.findOne({ email }).then(user => {
        if (user) {
            return res.status(400).json({ msg: 'User already exists!' });
        }

        const newUser = new User({
            name,
            email,
            password
        });

        //create salt & hash
        bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(newUser.password, salt, (err, hash) => {
                if (err) throw err;
                newUser.password = hash;
                newUser.save().then(user => {
                    jwt.sign(
                        { id: user.id },
                        config.get('jwtSecret'),
                        {
                            expiresIn: 3600
                        },
                        (err, token) => {
                            if (err) throw err;
                            res.json({
                                token,
                                user: {
                                    id: user.id,
                                    name: user.name,
                                    email: user.email
                                }
                            });
                        }
                    );
                });
            });
        });
    });
});

module.exports = router;

//错误屏幕截图

Screenshot of error

1 个答案:

答案 0 :(得分:0)

我发现这样做似乎有误:

您正在尝试发布以下字段({name, email, password}),但删除如下花括号:(name, email, password)

使用这种方式

//register user

    export const register = (name, email, password) => dispatch => {
        //headers
        const config = {
            headers: {
                'Content-Type': 'application/json'
            }
        };
    
        //request body
        const body = JSON.stringify({ name, email, password });
    
        axios
            .post('api/users', body, config)
            .then(res =>
                dispatch({
                    type: REGISTER_SUCCESS,
                    payload: res.data
                })
            )
            .catch(err => {
                dispatch(returnErrors(err.response.data, err.response.status, 'REGISTER_FAIL'));
                dispatch({
                    type: REGISTER_FAIL
                });
            });
    };