【问题标题】:Handling an Angular HTTP Request with a Bottle Server CORS not allowed不允许使用 Bottle 服务器 CORS 处理 Angular HTTP 请求
【发布时间】:2020-09-26 18:12:12
【问题描述】:

我正在尝试将数据从我的 Angular 9 应用程序提交到瓶子后端服务器。在客户端,我收到了 CORS 错误,即缺少“Access-Control-Allow-Origin”标头。它还说同源规则正在阻止请求。在后端它只打印状态代码 405。但是,当我通过 Postman 执行请求时,一切正常。我必须做哪些更改才能使其正常工作?我希望它也能在生产模式下工作。 这是我的代码: 角组件.ts:

onSubmit(form) {
    console.log(form.value);
    this.http.post('http://localhost:8080/contact', form.value).subscribe();
}

我的瓶子后端服务器:

@post('/contact')
def progress_contact():
    response.set_header('Content-Type', 'application/json')
    response.set_header('Access-Control-Allow-Origin', 'http://localhost:4200')
    response.set_header('Access-Control-Allow-Methods', 'PUT, GET, POST, OPTIONS, DELETE')
    response.set_header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Content-Type, Accept, Accept-Language, Origin, User-Agent')
    print(request)
    print(request.POST.moin)
    print(request.POST.email)
    return 'hello'

正如我所提到的,当通过 Postman 执行 POST 请求时,我在响应对象中得到“你好”,并且服务器也会打印我发送的值。

【问题讨论】:

  • OPTIONS的情况下,返回200 OK状态,中断链中的任何其他请求处理程序。
  • 对不起,你是什么意思?你建议我怎么做?
  • 您正在处理请求,这没关系,但您应该有一个请求过滤器,所有请求都应通过该过滤器,并且此过滤器将是处理 CORS 的正确位置。在该过滤器中,您应该将所有 CORS 代码放入您的 @post 注释函数中,并添加一个 if 立即返回 OK 状态,以防请求方法为 OPTIONS。不幸的是,我不是 Python 程序员,不能告诉你怎么做。
  • 谢谢!我只是这样做了,现在一切正常! :)

标签: angular http localhost bottle


【解决方案1】:

您需要在后端代码中允许 cors。 由于角度的预检请求而您遇到问题,并且您的后端代码不允许使用 cors。 有多个选项可以允许 cors,在这里你也可以使用 pypi 上的包。 https://pypi.org/project/bottle-cors/

【讨论】:

  • 我启用了 cors(请参阅服务器发送的标头)。实际上帮助我解决这个问题的是预检请求的提示(不知道它们存在)。所以我不得不启用 OPTIONS 方法,现在一切正常。谢谢! :)
  • 是的,OPTIONS 方法太棒了。
【解决方案2】:

这段代码为我解决了这个问题:

@route('/contact', method=['POST', 'OPTIONS'])
def progress_contact():
  if request.method == 'OPTIONS':
    response.set_header('Access-Control-Allow-Origin', '*')
    response.set_header('Access-Control-Allow-Methods', 'PUT, GET, POST, OPTIONS, DELETE')
    response.set_header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Content-Type, Accept, Accept-Language, Origin, User-Agent')

  else:
    print(request.json['email'])
    return 'hello'

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2018-07-28
    • 1970-01-01
    • 2018-11-12
    • 2016-08-05
    • 2013-10-06
    • 2018-04-17
    • 2019-04-11
    • 2017-07-31
    相关资源
    最近更新 更多