React Redux 将一个操作调度到另一个域进行身份验证



我正在使用omniauth-github策略,单击按钮后,我想将操作调度到另一个域(例如"https://github.com/login/oauth/authorize"(。但是,当使用调度时,这不起作用,因为浏览器会预检我的请求并与"没有'访问控制-允许-来源'产生共鸣。我可以通过使用 和 指向 url 来使其工作,然后它会将用户发送回我的后端以验证用户获取令牌存储它。但是如果没有调度,我必须发回我的站点在查询参数中生成的 JWT 令牌,并且由于我省略了我的操作创建者和化简器,因此我无法将其存储在 localStorage 中。有没有办法执行跨域调度?

export const loginGitHub = () => {
return dispatch => {
fetch('https://github.com/login/oauth/authorize?client_id=...&scope=user',{
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*',
},
mode: 'cors'
})
.then(resp=>resp.json())
.then(data => {
debugger
})
}
}

您需要向此方法提供 redux 存储的dispatch方法才能使其正常工作,这通常是通过将mapDispatchToProps与 redux 的connect()方法一起使用来完成的:https://github.com/reduxjs/react-redux/blob/master/docs/api.md

这是典型的流程,如果出于某种原因您需要在组件外部调用它,例如在挂载 React 应用程序之前(但在初始化 redux 存储之后(,这样的事情可以工作:

import { createStore } from 'redux'
const store = createStore();
export const loginGitHub = dispatch => {
return dispatch => {
fetch('https://github.com/login/oauth/authorize?client_id=...&scope=user',{
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*',
},
mode: 'cors'
})
.then(resp=>resp.json())
.then(data => {
debugger
})
}
}
loginGitHub(store.dispatch);

这在很大程度上是一种反模式,我建议正确使用需要mapDispatchToProps

创建商店 将应用包装在提供程序中,并将以前创建的应用商店作为道具提供给提供程序。 在组件中使用这样的connect()

import React, { Component } from 'react';
import { connect } from 'redux';
import { loginGitHub } from './wherever';
class ExampleComponent extends Component {
// whatever component methods you need
}
const mapDispatchToProps = dispatch => ({
loginGitHub: () => dispatch(logInGitHub())
})
export default connect(null, mapDispatchToProps)(ExampleComponent);

然后,您将能够在组件中使用this.props.loginGitHub()调用loginGitHub。

相关内容

最新更新