Почему моя конечная точка API Flask получает ошибку CORS, а другие аналогично запрограммированные конечные точки-нет?

#python #http #flask #cors #backend

Вопрос:

Проблема

У меня есть API-интерфейс Flask с двумя различными типами маршрутов. Я делаю запросы к своим конечным точкам API из JavaScript/D3.js заявление. Мне нужна помощь в устранении ошибки CORS.

Формат конечной точки

Один вид конечной точки соответствует формату http://127.0.0.1:5000/api/v0.1.0/infrastructure/primary_type/secondary_type

А другой вид следует формату http://127.0.0.1:5000/api/v0.1.0/infrastructure/primary_type/

Я получаю ошибку CORS для файла, следующего за форматом http://127.0.0.1:5000/api/v0.1.0/infrastructure/primary_type/

Ошибка CORS

Access to fetch at 'http://127.0.0.1:5000/api/v0.1.0/infrastructure/primary_type' from origin 'http://127.0.0.1:3000' 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.

Код конечной точки

Рабочая конечная точка

 @bp.route("<primary_type>/<secondary_type>")
def get_infrastructure(primary_type, secondary_type):
    infrastructure = ''
    if primary_type == 'null':
        infrastructure = shotgun_api.db.infrastructure.find({'properties.type.secondary': secondary_type}, projection = {'_id': False})
    else:
        infrastructure = shotgun_api.db.infrastructure.find({"$and": [{'properties.type.primary': primary_type},{'properties.type.secondary': secondary_type}]}, projection = {"_id": False})    
    
    response = jsonify([resource for resource in infrastructure])
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response
 

Ошибки, вызывающие конечную точку

 @bp.route('<primary_type>/')
def get_by_primary_type(primary_type):
    infrastructure = shotgun_api.db.infrastructure.find({'properties.type.primary': primary_type}, projection = {'_id': False}) 
    response = jsonify([resource for resource in infrastructure])
    response.headers.add("Access-Control-Allow-Origin", "*")
    return response
 

Ожидаемое поведение

Я ожидал бы, что использование того же response.headers.add... кода предоставит мне 200 OK статус, но по какой-то причине он работает только для более сложной конечной точки.

Сторона клиента JavaScript/D3.js

 for (let i = 0, num_draw_props = lyr.draw_props.length; i < num_draw_props;   i) {
          start_loading_layer();
          Promise.all(lyr.draw_props[i].src.map(x => lyr.draw_props[i].d3_fetch(x)))
            .then(function(files) {
              lyr.context.restore();
              lyr.context.save();
              return files;
            }).then(files => {
              transform_layer(lyr.context, transform);
              return files
            }).then(files => {
              console.time('draw_layer')
              lyr.draw_props[i].draw_layer(lyr.context, files);
              console.timeEnd('draw_layer')
            });
        }
 

Where d3_fetch is equal to d3.json() . When src is 'http://127.0.0.1:5000/api/v0.1.0/infrastructure/mines/coal' everything works fine, but when src is http://127.0.0.1:5000/api/v0.1.0/infrastructure/railroads I get the previously mentioned CORS error.

What I’ve tried

I have tried using Flask-CORS but was unable to get it accessible to my application despite installing it with pip. I would prefer to solve this without using Flask-CORS. I am otherwise at a loss for what to do here and any advice is appreciated.