30
21

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.

AngularJSからFlask APIを呼んで、No 'Access-Control-Allow-Origin...で怒られた時の対処法

Last updated at Posted at 2017-12-21

どうもmiyachi(@_38ch)です。
ローカルで起動していたFlask APIをAngularから呼ぶと、以下のようなエラーがでて、レスポンスを取得できなかった。

No 'Access-Control-Allow-Origin.Origin 'null' is therefore not allowed access.' header is present on the requested resource error

調べてみると、JavaScriptが別のドメイン/プロセスでホストされているHTTPリクエストを送ろうとすると出るエラーらしい。
Flask側で **CORS (Cross-Origin Resource Sharing)**を有効にしてあげる必要がある。

「Flask cross origin」でググると丁寧に書いてある。

インストール

pip install -U flask-cors

使い方

main.py
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, abort, make_response
from flask_cors import CORS # <-追加
import json

api = Flask(__name__)
CORS(api) # <-追加

@api.route('/', methods=['GET'])
def sample():

    result = {'result': 'Success!!'}

    return make_response(jsonify(result))

@api.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

if __name__ == '__main__':
    api.run(port=3000)
controller.js
var app = angular.module('myApp', []);
app.controller('myController', ['$scope', '$http', function($scope, $http) {

  var req = {
    method: 'GET',
    url: 'xxxxxxxxxxxxxxxxx'
  }

  $http(req).success(function(data, status, headers, config) {
    console.log(data);
  }).error(function(data, status, headers, config) {
    console.log(status);
  });
}]);

こんな感じでちゃんとAngularにレスポンスが返ってきました。
結構お手軽。

参考記事:
No 'Access-Control-Allow-Origin.Origin 'null' is therefore not allowed access.' header is present on the requested resource error(https://stackoverflow.com/questions/39912283/no-access-control-allow-origin-origin-null-is-therefore-not-allowed-access)

Flask-CORS(http://flask-cors.readthedocs.io/en/latest/)

30
21
1

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
30
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?