1

I only get the error when i try to make a GET of good chunk of data from yahoofinance, when i do small requests it works good. The front is a react deployed on Vercel, and the backend is flask deployed on Heroku. This is what im doing:

Flask App:

from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from utils import *


app = Flask(__name__)
cors = CORS(app, resources={
            r"/api/*": {"origins": "*"}}, support_credentials=True)


@app.route('/')
@cross_origin()
def index():
    return "Home"


@app.route('/api', methods=['GET'])
@cross_origin()
def api():
    return{
        "tutorial": "Flask React Herokuu"
    }


@app.route('/api/minsmax', methods=['GET'])
@cross_origin(origin='https://jjtrading-rfripp2.vercel.app', headers=['Content-Type', 'Authorization'])
def prices():
    days_back = request.args.get('days_back')
    coins_quantity = request.args.get('coins_quantity')
    response = jsonify(get_coins_in_min_max(days_back, coins_quantity))
    return response

React:

import { useState } from "react";
import axios from "axios";
import "./MinsMax.css";
import CoinsExcluded from "./CoinsExluded";
export const MinsMax = () => {
  const [state, setState] = useState({});
  const [result, setResult] = useState();
  const handleSubmit = (event) => {
    event.preventDefault();
    axios
      .get(
        `https://jjtradingapi.herokuapp.com/api/minsmax?days_back=${state.daysBack}&coins_quantity=${state.coinsQuantity}`,
        /* {
          headers: {
            xhrFields: {
              withCredentials: true,
            },
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            "Access-Control-Allow-Origin": "*",
          },
        } */
      )
      .then((result) => {
        console.log(result.data);
        setResult(result.data);
      });
    handleReset();
  };
  return(<div></div>)
};

The GET is succesfull when i do like 5 coins and a few days, but when i start to do more,i get this CORS error:

On the console:

Access to XMLHttpRequest at 'https://jjtradingapi.herokuapp.com/api/minsmax?days_back=2d&coins_quantity=50' from origin 'https://jjtrading-rfripp2.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
VM26:1          GET https://jjtradingapi.herokuapp.com/api/minsmax?days_back=2d&coins_quantity=50 net::ERR_FAILED 503

And in network:

Request URL: https://jjtradingapi.herokuapp.com/api/minsmax?days_back=2d&coins_quantity=50
Request Method: GET
Status Code: 503 
Referrer Policy: strict-origin-when-cross-origin
Cache-Control: no-cache, no-store
Connection: keep-alive
Content-Length: 506
Content-Type: text/html; charset=utf-8
Date: Sat, 26 Feb 2022 11:32:24 GMT
Server: Cowboy
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: es-419,es;q=0.9,en;q=0.8
Connection: keep-alive
Host: jjtradingapi.herokuapp.com
Origin: https://jjtrading-rfripp2.vercel.app
Referer: https://jjtrading-rfripp2.vercel.app/

The other routes that are simple,they work good. Any idea what can be the issue? Thanks so much in advance :)

Edit: maybe a function that has Try Except code makes it break? (happens when i request 50+ coins and when i get the CORS error). When i request to local host,i get the exceptions and the GET returns 200,but when i request to the heroku deploy, 503 with the CORS error. This is the function with the Try Except:

def get_mins_max_list(timeframe, amount_of_coins):
    result = {
        "mins": [],
        "max": [],
    }
    today = {
        "mins": None,
        "max": None,
        "tracked": 0,
        'errors': []
    }
    coins = getSymbols(amount_of_coins)
    coins_usd = symbols_usd(coins)
    for coin in coins_usd:
        try:
            minmax = get_min_max_price(coin, timeframe)
            result['mins'].append(minmax['min'])
            result['max'].append(minmax['max'])
            today['tracked'] += 1
        except IndexError:
            today['errors'].append(coin)
            continue
    today['mins'] = filter_today(result['mins'])
    today['max'] = filter_today(result['max'])
    return today
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Joa0
  • 69
  • 9
  • What CORS error message are you getting? Add it to your question. Also, add the client code responsible for sending the problematic request. – jub0bs Feb 26 '22 at 09:13
  • I updated my post with the inf, thanks jub0bs! – Joa0 Feb 26 '22 at 11:39
  • Is the missing `Access-Control-*` header perhaps a side-effect of the fact that the request has failed (HTTP status 503)? Also, you misspelled a header name as `'Content- Type'` (with a space) in your `@cross_origin` declaration. – Heiko Theißen Feb 26 '22 at 12:50
  • Good catch on the misspell,i corrected but the problem persist. Thanks Heiko! It might be something with the function that calls it, wich has try except code and it has many exceptions (when i do the request of requesting 50+ coins), but when i request to local host, they all go through with status code 200 – Joa0 Feb 26 '22 at 12:55
  • I edited the post with the function with Try Except if it has anithing to do maybe? – Joa0 Feb 26 '22 at 13:06
  • @Joa0 Drop that trailing slash in `https://jjtrading-rfripp2.vercel.app/`. – jub0bs Feb 26 '22 at 15:22
  • Good catch there jub0bs too,thanks! Problem still persists tho, the weird thing is when the request is small data like 2d 5 coins, its no problem, it does it when i start to ask for larger coins (50) etc – Joa0 Feb 26 '22 at 15:30
  • When i do it through postman to the heroku url with 50 coins,i get the heroku application error response. When i do fewer coins like 5, its alright – Joa0 Feb 26 '22 at 17:25
  • ever find a solution to this? I am about to look at Flask to avoid the CORS problems I am having in ReactJS and dont want to run into it again since I want Flask to be the solution. – mdkb Jul 15 '22 at 00:48
  • Yes,problem was a side effect that the requesting response was taking over 30 seconds,which is a gunicorn parameter i think, can change that on its configuration if needed – Joa0 Jul 16 '22 at 03:41

0 Answers0