混合React路由器用于SPA和Express路由器用于OAuth(API调用)

时间:2017-06-15 07:30:04

标签: reactjs express oauth react-router

我尝试使用React Router和github oauth做一个React应用程序。

但Github Oauth不支持cors api呼叫,也不保证在前端存储密钥。

所以我计划在Express中托管我的反应应用程序并使用express来执行后端github oauth调用。

然后,我发现当Express Router与React-Router混合时,Express Router将无法运行,可能被React-Router阻止。

快递代码在这里:

const express = require('express')
const randomstring = require('randomstring');
const axios = require('axios');
const app = express()

let state = '';

app.get('/authorize', function (req, res) {
  state = randomstring.generate();
  res.redirect('http://github.com/login/oauth/authorize?' + 'client_id=3ba48xxxx6d6d0&state=' + state);
})

app.get('/auth-callback', function (req, res) {
  if (state === req.params.state) {
    axios.post('https://github.com/login/oauth/access_token', {
      client_id: '3ba48xxxx6d6d',
      client_secret: 'xxxx',
      code: req.params.code
    }).then(function (data) {
      console.log(data);
    });
  };
});

app.use(express.static('build'))

app.get('*', function(req, res) {
    res.sendfile('./build/index.html');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

这可能与这个React Router & Express Conflicts有关,我认为这是同一个想法。

因此,当我将登录按钮链接到'/ authorize'时,它没有被快递拦截。

登录按钮

import React from 'react';
import { Redirect } from 'react-router-dom'
import authService from '../GithubAuth/AuthService.js';

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      redirectToReferrer: false
    };
  }
  state = {
    redirectToReferrer: false
  }

  login = () => {
    authService.authenticate(() => {
      this.setState({ redirectToReferrer: true })
    })
  }

  render() {
    const { from } = this.props.location.state || { from: { pathname: '/' } }
    const { redirectToReferrer } = this.state

    if (redirectToReferrer) {
      return (
        <Redirect to={from} />
      )
    }

    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <button onClick={this.login}>Log in</button>
      </div>
    )
  }
}

export default Login;

authenService.js

import * as Cookies from "js-cookie";

export default {
  isAuthenticated: false,
  authenticate(cb) {
    const githubToken = Cookies.get('github_token');
    if (githubToken) {
      this.isAuthenticated = true
    } else {
      global.location.href = '/authorize';
    }
    setTimeout(cb, 100) // fake async
  },
  signout(cb) {
    this.isAuthenticated = false
    setTimeout(cb, 100)
  }
}

有些专家可以解释原因并告诉我如何正确使用它吗?

0 个答案:

没有答案