【发布时间】:2019-10-21 18:22:12
【问题描述】:
我有一个 JWT 授权系统。当我登录时,我将 JWT 令牌从服务器放入本地存储。
我还有TariffsApiComponent,它在TariffsReducer 中调用getTariffs。
此 thunk 在标头中使用此 JWT 令牌获取关税的 http 请求,但是当我检查来自服务器的响应时,我没有得到 resultCode = 0(成功请求)。
我试图在服务器上检查我的令牌有什么问题,但我看到了。
还不得不说,如果我重新加载页面而不是从本地存储中删除令牌它正在工作!
组件
TariffsContainer.jsx
import React, { Component } from "react";
import { connect } from "react-redux";
import Tariffs from "./Tariffs";
import { changeTariffStatus, getTariffs } from "../../../redux/tariffsReducer";
import withAuthRedirect from "../../../hoc/withAuthRedirect";
import { compose } from "redux";
class TariffsApiComponent extends Component {
componentDidMount() {
this.props.getTariffs();
}
render() {
return (
<Tariffs
tariffId={this.props.tariffId}
tariffs={this.props.tariffs}
changeTariffStatus={this.props.changeTariffStatus}
/>
);
}
}
...
tariffsReducer.js
...
export const setTariffs = (tariffs, tariffId) => ({
type: SET_TARIFFS,
tariffs,
tariffId
});
export const getTariffs = () => dispatch => {
getTariffsAPI().then(response => {
if (response.resultCode === 0) {
let { tariffs, tariffId } = response;
dispatch(setTariffs(tariffs, tariffId));
}
});
};
...
请求
...
const instance = axios.create({
headers: {
"x-access-token": localStorage.getItem("token")
}
});
export const getTariffsAPI = () => {
return instance
.get(`http://localhost:1337/tariffs`)
.then(response => {
return response.data.data});
};
...
中间件
let checkToken = (req, res, next) => {
let token = req.headers["x-access-token"] || req.headers["authorization"];
if (token.startsWith("Bearer ")) {
token = token.slice(7, token.length);
}
console.log(req.headers["x-access-token"]);
if (token) {
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
return res.json({
success: false,
message: "Token is not valid"
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.json({
success: false,
message: "Auth token is not supplied"
});
}
};
错误
登录后我在服务器上看到的内容
【问题讨论】:
-
如果将 console.log(response) 添加到 getTariffsAPI().then(response => {console.log(response); 会显示什么
-
imgur.com/21mntgv 。并在请求中访问令牌imgur.com/4HaalwK
-
如果日志没有给你明确的输出,那么也许你可以试试
JSON.Stringify这个对象看看它是什么。 -
imgur.com/LVsh4ak 空对象,但是为什么我在这里设置它imgur.com/dp7okD6