1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flask で Access to fetch at ... from origin ... has been blocked by CORS policy

Last updated at Posted at 2020-06-22

対応

after_request を使って、レスポンスを フック して、ヘッダを書き換えました。

#
# 対話モード >>> に
# コピペで実行できます。
#
from flask import Flask, jsonify


app = Flask(__name__)

@app.route('/')
def index():
    return jsonify({'message': 'Hello, world!'})

@app.after_request
def set_cors_header(response):
    クライアント側のアドレスとポート = 'http://127.0.0.1:8080'
    response.headers['Access-Control-Allow-Origin'] = クライアント側のアドレスとポート
    response.headers['Access-Control-Allow-Method'] = 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS'  # noqa: E501
    response.headers['Access-Control-Allow-Headers'] = 'Content-type,Accept,X-Custom-Header'  # noqa: E501
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Max-Age'] = '86400'
    return response

app.run()

背景

CORS に引っかかると以下のようなエラーが表示されます。

Access to fetch
at 'http://127.0.0.1:5000/'  サーバ (Flask) 側の IP アドレスとポート
from origin 'http://127.0.0.1:8080' クライアント側の IP アドレスとポート番号
has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present
on the requested resource.
If an opaque response serves your needs,
set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

いくつか他にも対応方法はあるようなのですが、

そこまで込み入ったことはしないので、とりあえず、簡単に逃しました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?