Python 金字塔应用程序中的 CORS 预取错误

问题描述 投票:0回答:1

我有一个用reactjs构建的web应用程序前端,并调用使用python金字塔构建的api。

当我在本地开发中测试此应用程序时,我将 web 应用程序部署在 localhost:6543 中,将 python 应用程序部署在 localhost:3000 中。

调用 python 应用程序时出现 CORS 预取错误。

这是我的 JS 调用 -

const onFinish = (values) => {
    fetch(`${baseUrl}login`, {
      method: "POST",
      mode: 'no-cors',
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "http://localhost:3000",
      },
      body: JSON.stringify(values),

Python 应用程序添加 cors 标头 -

from pyramid.config import Configurator
from invest_web.authentication.security import SecurityPolicy
from pyramid.response import Response
from pyramid.events import NewRequest
from invest_web.models.models import User, Issuer

def add_cors_headers_response_callback(event):
    def cors_headers(request, response):
        
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'POST,GET,DELETE,PUT,OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'access-control-allow-origin,content-type'
        response.headers['Access-Control-Allow-Credentials'] = 'true'        
    event.request.add_response_callback(cors_headers)

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    with Configurator(settings=settings) as config:
        config.include('pyramid_jinja2')

        config.set_security_policy(
            SecurityPolicy(
                secret=settings['invest_web.secret']
            ),
        )

        config.add_subscriber(add_cors_headers_response_callback, NewRequest)
        config.include('.routes')
        config.include('.models')
        config.scan()

    return config.make_wsgi_app()

python pyramid
1个回答
0
投票

在执行

404 Not Found
请求时,它会显示
OPTIONS

我的猜测是,除非找到视图,否则不会调用您的事件处理程序,但我可能是错的。

© www.soinside.com 2019 - 2024. All rights reserved.