Вызов звонок завис и ничего не отвечает - PullRequest
0 голосов
/ 01 апреля 2020

У меня есть компонент с именем ComboBox. js и сервер PHP работает. В методе componentDidMount я делаю вызов извлечения, но затем браузер зависает на "http://localhost: 3000 / search? Code = b12a2302e2d0f2b22143b7b4e0472901b2c1b9a8 & state = xyz ".

Вот компонент ComboBox. js:

import React from "react";
import classes from "./ComboBox.module.css";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import axios from "axios";
import fetch from "fetch";

class ComboBox extends React.Component {
  state = {
    contests: []
  };

  componentDidMount() {
    let str;
    try {
      console.log("hey");
      str = window.location.href.split("=")[1].split("&")[0];
      console.log(str);
    } catch {
      console.log("Catch");
      window.location.href = "http://localhost:8000/";
    }
    fetch(`http://localhost:8000/index.php/?code=${str}`, {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "application/json",
      },
      method: "GET",
    })
      .then((res) => {
        console.log(res);
        return res.json();
      })
      .then((res) => {
        console.log(res);
        var tk = res.access_token;
        var rtk = res.refresh_token;
        localStorage.setItem("aut_token", tk);
        localStorage.setItem("ref_token", rtk);
      })
      .catch((err) => {
        console.log(err.response);
      });

      console.log(localStorage.getItem("aut_token"))

    while (localStorage.getItem("aut_token") === null) {}



    axios({
      method: "get",
      url: `https://api.codechef.com/contests/?fields=&sortBy=&sortOrder=`,
      headers: {
        Accept: "application/json",
        Authorization: `Bearer ${localStorage.getItem("aut_token")}`
      }
    })
      .then(res => {
        res = res.data.result.data.content.contestList;
        this.setState({ contests: res });
      })
      .catch(err => {
        console.log("NOT DONE");
        console.log(err.response);
      });
  }

  render() {
    return (
      <div className={classes.ComboBoxPage}>
        <header>
          <div className={classes.header}>
            <img
              className={classes.himage}
              src={require("../assets/finalLogo.jpeg")}
              alt="CodeChef"
            />
          </div>
        </header>
        <img src={require("../assets/wp1828902.png")} alt="" />
        <p className={classes.heading}>COMPETE</p>
        <div className={classes.ComboBox}>
          <Autocomplete
            id="combo-box-demo"
            options={this.state.contests}
            getOptionLabel={option => `${option.code} - ${option.name}`}
            onChange={(a, b, c) =>
              this.props.history.push(`/contest/${b.code}`)
            }
            style={{ width: 300 }}
            renderInput={params => (
              <TextField {...params} label="All Contests" variant="outlined" />
            )}
          />
        </div>
      </div>
    );
  }
}

export default ComboBox;

На всякий случай: Мой маршрутизатор. js компонент

import React from "react";
import App from "./App";
import ComboBox from "./ComboBox/ComboBox";
import NotFound from "./ErrorHandling/NotFound";
import Problem from "./Problem/Problem";
import Contest from "./Contest/Contest";
import Ranking from "./Ranking/Ranking"
import { BrowserRouter, Route, Switch } from "react-router-dom";

const Router = () => (
  <BrowserRouter>
    <Switch>
      <Route exact path="/" component={App} />
      <Route exact path="/search" component={ComboBox} />
      <Route exact path="/contest/:contest_code" component={Contest} />
      <Route exact path="/contests/:contest_code/problems/:problem_code" component={Problem} />
      <Route exact path="/rankings/:contest_code" component={Ranking}/>
      <Route component={NotFound} />
    </Switch>
  </BrowserRouter>
);

export default Router;

Вот индекс. php файл:

<?php 

if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');
}


if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

function take_user_to_codechef_permissions_page($config){

    $params = array('response_type'=>'code', 'client_id'=> $config['client_id'], 'redirect_uri'=> $config['redirect_uri'], 'state'=> 'xyz');
    header('Location: ' . $config['authorization_code_endpoint'] . '?' . http_build_query($params));
    die();
}

function generate_access_token_first_time($config, $oauth_details){

    $oauth_config = array('grant_type' => 'authorization_code', 'code'=> $oauth_details['authorization_code'], 'client_id' => $config['client_id'],
                          'client_secret' => $config['client_secret'], 'redirect_uri'=> $config['redirect_uri']);
    $response = json_decode(make_curl_request($config['access_token_endpoint'], $oauth_config), true);
    $result = $response['result']['data'];

    $oauth_details['access_token'] = $result['access_token'];
    $oauth_details['refresh_token'] = $result['refresh_token'];
    $oauth_details['scope'] = $result['scope'];

    return $oauth_details;
}

function generate_access_token_from_refresh_token($config, $oauth_details){
    $oauth_config = array('grant_type' => 'refresh_token', 'refresh_token'=> $oauth_details['refresh_token'], 'client_id' => $config['client_id'], 'client_secret' => $config['client_secret']);
    $response = json_decode(make_curl_request($config['access_token_endpoint'], $oauth_config), true);
    $result = $response['result']['data'];

    $oauth_details['access_token'] = $result['access_token'];
    $oauth_details['refresh_token'] = $result['refresh_token'];
    $oauth_details['scope'] = $result['scope'];

    return $oauth_details;

}


function make_curl_request($url, $post = FALSE, $headers = array())
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    if ($post) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
    }

    $headers[] = 'content-Type: application/json';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($ch);
    return $response;
}

function main(){

    $config = array('client_id'=> '', //assume I have the right id and secret placed here
        'client_secret' => '',
        'api_endpoint'=> 'https://api.codechef.com/',
        'authorization_code_endpoint'=> 'https://api.codechef.com/oauth/authorize',
        'access_token_endpoint'=> 'https://api.codechef.com/oauth/token',
        'redirect_uri'=> 'http://localhost:3000/search',
        'website_base_url' => 'http://localhost:3000/');

    $oauth_details = array('authorization_code' => '',
        'access_token' => '',
        'refresh_token' => '');

    if(isset($_GET['code'])){
        $oauth_details['authorization_code'] = $_GET['code'];
        $oauth_details = generate_access_token_first_time($config, $oauth_details);
        echo json_encode($oauth_details);
    }
    else
    if(isset($_GET['ref_token'])){
        $oauth_details['refresh_token'] = $_GET['ref_token'];
        $oauth_details = generate_access_token_from_refresh_token($config, $oauth_details);
        echo json_encode($oauth_details);
    }
    else{
        take_user_to_codechef_permissions_page($config);
    }
}

main();

1 Ответ

1 голос
/ 01 апреля 2020

вам не нужно импортировать "fetch"

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...