我正在使用MERN堆栈结构和Redux,我遇到了isomorphic-fetch模块的问题。
我想从会话中获取用户信息,但isomorphic-fetch模块似乎是其请求与用户会话分开。
以下是视图调度动作以从会话中获取用户信息。
MainView.jsx:
None
以下是动作,减速器和路由器。
actions.js(仅限相关代码):
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import * as Actions from '../../redux/actions/actions';
class MainView extends React.Component {
constructor(props) {
super(props);
this.displayName = 'MainView';
}
componentWillMount() {
if (this.props.showMessageModal.message !== '') {
this.props.dispatch(Actions.showMessageModal());
}
this.props.dispatch(Actions.fetchUserSession());
}
render() {
const renderTemp = () => {
if (this.props.user) {
return <div>{ JSON.stringify(this.props.user) }</div>;
}
};
return (
<div>
MainView
{ renderTemp() }
</div>
);
}
}
MainView.contextTypes = {
router: React.PropTypes.object,
};
function mapStateToProps(store) {
return {
showMessageModal: store.showMessageModal,
user: store.user,
};
}
MainView.propTypes = {
showMessageModal: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
user: PropTypes.object,
};
export default connect(mapStateToProps)(MainView);
reducer_user.js(在索引缩减器中组合):
import * as ActionTypes from '../constants/constants';
import Config from '../../../server/config';
import fetch from 'isomorphic-fetch';
const baseURL = typeof window === 'undefined' ? process.env.BASE_URL || (`http://localhost:${Config.port}`) : '';
export function getUserSession(user) {
return {
type: ActionTypes.GET_USER_SESSION,
user,
};
}
export function fetchUserSession() {
return (dispatch) => {
return fetch(`${baseURL}/api/session-user`)
.then((response) => response.json())
.then((response) => dispatch(getUserSession(response.user)));
};
}
user.router.js(api router):
import * as ActionTypes from '../constants/constants';
export const user = (state = null, action) => {
switch (action.type) {
case ActionTypes.GET_USER_SESSION :
return action.user;
default:
return state;
}
};
登录后,当我直接在浏览器上访问'/ api / session-user'时,我可以看到这样的用户信息。
但是当我加载MainView并调度动作时,user.router.js中的'req.user'会返回'undefined'。
请猜猜错了。这将非常有帮助。
答案 0 :(得分:0)
我已经找到了问题所在。 'isomorphic-fetch'未设置请求cookie,因此无法从cookie中获取其会话。我已经在action.js中更改了我的代码,如下所示,并且它运行良好。
export function fetchUserSession() {
return (dispatch) => {
return $.ajax({
url: `${baseURL}/api/session-user`,
success: (response) => {
dispatch(getUserSession(response));
},
});
};
我参考了这个页面 - https://github.com/matthew-andrews/isomorphic-fetch/issues/75
答案 1 :(得分:0)
您只需添加credentials
参数:
export function fetchUserSession() {
return (dispatch) => {
return fetch(`${baseURL}/api/session-user`, {credentials: 'same-origin'})
.then((response) => response.json())
.then((response) => dispatch(getUserSession(response.user)));
};
}