I face CORS when flask provide static file. but Flask-Cors dose not work correctly….

Env

  • Flask==1.1.1

How to solve

Use decorator and send_from_directory, instead of default static doc

from flask import Flask, send_from_directory
app = Flask(__name__, static_url_path="")
def res_decorator(f):
  def func(*args, **kwargs):
    resp = make_response(f(*args, **kwargs))
    resp.cache_control.no_cache = True
    # avoid CORS
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
  return update_wrapper(func, f)

@app.route('/static/<path:path>')
@res_decorator
def static_files(path):
  return send_from_directory('static', path,cache_timeout=0)

Ref

send_from_directory
decorator