Axios GET请求不喜欢未定义的标头(x-auth-token)

时间:2019-09-23 22:20:02

标签: node.js reactjs redux axios

所以我有一个react应用,其中导航栏组件在刷新后拒绝显示。如果标头x-auth-token值未定义,则对端点的axios调用似乎无效。

我将sethAuthtoken随机设置为垃圾值,并给出了 401错误,这是有道理的,但是如果localstorage.token没有值,则在以下消息超时之前我什么都没有得到 net::ERR_EMPTY_RESPONSE

这是操作文件,导航栏从以下位置引用: Auth.js

import setAuthToken from '../utils/setAuthToken';

export const loadUser = () => async (dispatch) => {     if
 (localStorage.token) {         setAuthToken(localStorage.token);   }

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

try {
    const res = await axios.get("/api/auth", config);

    dispatch({
        type: USER_LOADED,
        payload: res.data
    });
} catch (err) {
    dispatch({
        type: AUTH_ERROR
    });
}};

这是后端路线

router.get("/", auth, async (req, res) => {
try {
    const user = await User.findById(req.user.id).select("-password");
    res.json(user).status(200);
} catch (error) {
    console.error(error.message);
    res.status(500).send("Server error");
}});

这是Navbar组件代码,它调用操作

import React, { Fragment } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { logout } from "../../actions/auth";

const Navbar = ({ auth: { isAuthenticated, loading }, logout }) => {
    const authLinks = (
        <ul>
            <li>
                <a onClick={logout} href="!#">
                    <i className="fas fa-sign-out-alt" />{" "}
                    <span className="hide-sm">Logout</span>
                </a>
            </li>
        </ul>
    );
    const guestLinks = (
        <ul>
            <li>
                <a href="#!">Developers</a>
            </li>
            <li>
                <Link to="/register">Register</Link>
            </li>
            <li>
                <Link to="/login">Login</Link>
            </li>
        </ul>
    );//will load guestlinks if not authenticated, authlinks if authenticated
    return (
        <nav className="navbar bg-dark">
            <h1>
                <Link to="/">
                    <i className="fas fa-code"></i> DevConnector
                </Link>
            </h1>
            {loading ? null : (
                <Fragment> {isAuthenticated ? authLinks : guestLinks} </Fragment>
            )}
        </nav>
    );
};

Navbar.propTypes = {
    logout: PropTypes.func.isRequired,
    auth: PropTypes.object.isRequired
};

const mapStateToProps = (state) => ({
    auth: state.auth
});

export default connect(
    mapStateToProps,
    { logout }
)(Navbar);

1 个答案:

答案 0 :(得分:0)

当本地存储中没有令牌时,我只是将一个else语句放入auth操作文件中,以将AUTH_ERROR分发给reducer。

export const loadUser = () => async dispatch => {
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  } else {
    dispatch({
      type: AUTH_ERROR
    });
  }