与角瓶REST风格的跨域问题:PUT,OPTIONS方法风格、方法、问题、REST

2023-09-10 16:01:54 作者:恍然_ _如梦、

我已经开发了一个小的只写REST API与瓶宁静的接受来自少数,可以潜在地更改IP地址的客户端PUT请求。我的客户端嵌入运行AngularJS前端铬的客户;他们身份验证我用一个简单的法宝API - 这是足以让我的规模十分有限。

I've developed a small write-only REST api with Flask Restful that accepts PUT request from a handful of clients that can potentially have changing IP addresses. My clients are embedded Chromium clients running an AngularJS front-end; they authenticate with my API with a simple magic key -- it's sufficient for my very limited scale.

我测试目前正在部署我的API,我注意到角客户端试图给OPTIONS HTTP方法发送给我的瓶服务。我的API同时将回复一个404(因为我没有写一个OPTIONS处理程序还没有,只有一个PUT处理程序)。似乎发送未POST或GET跨域请求时,角将在服务器发送一个$ P $对 - 飞行OPTIONS方法以确保跨域请求被接受之前发送的实际请求。是吗?

I'm testing deploying my API now and I notice that the Angular clients are attempting to send an OPTIONS http methods to my Flask service. My API meanwhile is replying with a 404 (since I didn't write an OPTIONS handler yet, only a PUT handler). It seems that when sending cross-domain requests that are not POST or GET, Angular will send a pre-flight OPTIONS method at the server to make sure the cross-domain request is accepted before it sends the actual request. Is that right?

不管怎样,我怎么让所有的跨域PUT请求烧瓶REST的API?我用交叉domaion装饰带(非宁静)瓶实例之前,但我需要写一个选项处理程序,以及进入我的API?

Anyway, how do I allow all cross-domain PUT requests to Flask Restful API? I've used cross-domaion decorators with a (non-restful) Flask instance before, but do I need to write an OPTIONS handler as well into my API?

推荐答案

我重写我的瓶的后端与我PUT响应的访问控制 - 允许 - 产地标头回答解决了这个问题。此外,我在瓶的应用程序创建了一个选项处理程序来回答选项的方法按照我读了HTTP RFC。

I resolved the issue by rewriting my Flask backend to answer with an Access-Control-Allow-Origin header in my PUT response. Furthermore, I created an OPTIONS handler in my Flask app to answer the options method by following what I read in the http RFC.

在PUT方法的返回是这样的:

The return on the PUT method looks like this:

return restful.request.form, 201, {'Access-Control-Allow-Origin': '*'} 

我的期权方法处理程序是这样的:

My OPTIONS method handler looks like this:

def options (self):
    return {'Allow' : 'PUT' }, 200, \
    { 'Access-Control-Allow-Origin': '*', \
      'Access-Control-Allow-Methods' : 'PUT,GET' }

@tbicr是正确的:容量瓶并自动接听选项适合你的方法。然而,在我的情况下,它是不发射与答案的访问控制 - 允许 - 产地标头,所以我的浏览器越来越从似乎意味着跨域请求不被允许的API的答复。我重载的选项在我的情况下请求并添加ACAO头,并且浏览器似乎满足于这一点,随访选项在端起还曾。

@tbicr is right: Flask DOES answer the OPTIONS method automatically for you. However, in my case it wasn't transmitting the Access-Control-Allow-Origin header with that answer, so my browser was getting a reply from the api that seemed to imply that cross-domain requests were not permitted. I overloaded the options request in my case and added the ACAO header, and the browser seemed to be satisfied with that, and followed up OPTIONS with a PUT that also worked.