简体   繁体   中英

flask-cors Control-Allow-Origin'

Trying to execute simple json request on local server combined with Python and django.

my apiview.py

from rest_framework import generics
from django.shortcuts import get_object_or_404
from .jsonserializer import GroupSerializer, SubgroupSerializer, ProductsSerializer
from .models import pGroups, pSubgroups, Products
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/Group/")
# @cross_origin()

# Create your views here.

class GroupList(generics.ListCreateAPIView):
    queryset = pGroups.objects.all()
    serializer_class = GroupSerializer

Jquery script

let dropdown = $('#locality-dropdown');

dropdown.empty();

dropdown.append('<option selected="true" disabled>Choose product group</option>');
dropdown.prop('selectedIndex', 0);

const url = 'http://127.0.0.1:8000/Group/';

// Populate dropdown with list of provinces
$.getJSON(url, function (data) {
  $.each(data, function (key, entry) {
    console.log(entry.name);
    dropdown.append($('<option></option>').attr('value', entry.abbreviation).text(entry.name));
  })
});

And after all i log in console smthng like :

Failed to load http://127.0.0.1:8000/Group/ : No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

What i'm trying is : Flask cors but seems im missing something in apiview.py .

PS I'm complete beginner in web. Edit: With postman i get the response

[
    {
        "id": 1,
        "group_chiper": "01",
        "group_shortcut": "DRN",
        "group_name": "Drink",
        "operator": 2
    },
    {
        "id": 2,
        "group_chiper": "02",
        "group_shortcut": "ML",
        "group_name": "Meals",
        "operator": 1
    }
]

Based on Robin comment :

django-cors-headers is one of approaches.

Using command line install it to your root project :

pip install django-cors-headers

If you are using environment you may install to it root project folder and reset the environment.

Add the installed app to your

settings.py

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware or Whitenoise's WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

The part i was missing is to add in settings.py

line of code

CORS_ORIGIN_ALLOW_ALL = True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM