我正在尝试制作一些中间件,如果它已经过期,它会刷新我的JWT。我目前有这个中间件:
events.js:160
throw er; // Unhandled 'error' event
^
TypeError: Cannot convert undefined or null to object
at C:\Users\S\Desktop\insta\back\server.js:43:24
at Query.<anonymous> (C:\Users\S\Desktop\insta\back\node_modules\mongoose\li
b\model.js:3800:16)
at C:\Users\S\Desktop\insta\back\node_modules\kareem\index.js:277:21
at C:\Users\S\Desktop\insta\back\node_modules\kareem\index.js:131:16
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
我希望调用refreshToken()函数来启动进程,但到目前为止,即使是refreshToken中的console.log()也没有调用:
import { isTokenExpired, refreshToken } from '../modules/auth/auth.service'
export const jwt = store => next => action => {
if (typeof action === 'function') {
console.log("Middleware triggered:", action);
var theState = store.getState();
if (theState.auth && theState.auth.authToken && isTokenExpired(theState.auth.authToken)) {
console.log('This is logging')
//this function is not being called
refreshToken(theState.auth.refreshToken);
}
}
return next(action)
}
此外,在刷新令牌时,refreshToken函数内部将是异步的。我想在reducer中设置一个“REFRESH_TOKEN_PENDING”类型,一旦收到响应,就将“REFRESH_TOKEN_SUCCESS”发送给reducer。中间件可以实现吗?
由于
答案 0 :(得分:1)
您必须发送 refreshToken()
。如果您有权访问dispatch()
jwt
功能,则应将其称为dispatch(refreshToken())
。
考虑到我不确定您是如何触发jwt
操作的,我认为这是一个有效解决方案,可以轻松触发操作中的中间件功能:
// ================
// Container file
// ================
import {connect} from "react-redux";
import { bindActionCreators } from "redux";
// ... other
function mapActionsToProps(dispatch) {
return bindActionCreators({
jwt: path_to_actions_file.jwt
}, dispatch)}
const mapStateToProps = (state) => ({
// ... your state properties
});
export default connect(mapStateToProps, mapActionsToProps)(YourComponent); // <== YourComponent has to be a React Component
// ==============
// Actions file
// ==============
export const setConvertTypeActive = store => dispatch => {
console.log('This is logging.');
dispatch(refreshToken("md5Token"));
}
export const refreshToken = refreshToken => dispatch => {
console.log('Should log now.');
}
关于你的上一个问题,是的,你可以创建类似于refreshToken
动作的中间件来设置减速器的一些状态。检查以下代码:
// ==============
// Actions file
// ==============
export const refreshToken= {
pending: () => ({
// "REFRESH_TOKEN_PENDING"
}),
success: (data) => ({
// "REFRESH_TOKEN_SUCCESS"
})
};