启用 Webiopi CORS 请求

Enable Webiopi CORS request

我想在 Raspberry 上的浏览​​器 运行 中从我的 angular 应用程序调用 Webiopi REST API。由于 Webiopi HTTP 服务器不允许 CORS 请求,我用 apache 创建了一个代理来发送 Header add "Access-Control-Allow-Origin" "*" header.

这工作正常,但是调用 REST API 会抛出许多错误,主要是因为浏览器会在 CORS 请求检查是否允许时向服务器发送 OPTIONS 请求。但是 webiopi http 处理程序根本不处理 OPTIONS 动词。

所以我开始在 python 零经验的情况下自己将其写入代码。在文件 python/webiopi/protocols/http.py 中我在最后添加了:

def do_OPTIONS(self):
    self.send_response(200,"ok")
    self.send_header("Access-Control-Allow-Origin", "*")
    self.send_header("Access-Control-Allow-Methods", "POST,GET,OPTIONS")
    self.send_header("Access-Control-Allow-Headers", "Authorization")
    self.send_header("Access-Control-Allow-Headers", "Content-Type")
    self.end_headers()

现在它不会抛出任何错误,但不会给我正确的 GET 请求响应。它只是在选项之后停止。请求和响应如下所示:

请求headers:

OPTIONS /GPIO/1/value HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://192.168.1.108:51443
User-Agent: Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Raspbian Chromium/65.0.3325.181 Chrome/65.0.3325.181 Safari/537.36
Access-Control-Request-Headers: authorization
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: hu-HU,hu;q=0.9,en-US;q=0.8,en;q=0.7

响应headers:

HTTP/1.1 200 OK
Date: Fri, 23 Nov 2018 22:06:28 GMT
Server: WebIOPi/0.7.1/Python3.5
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,POST,OPTIONS
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked

常规(来自 chrome 网络选项卡):

Request URL: http://localhost:8000/GPIO/1/value
Request Method: OPTIONS
Status Code: 200 OK
Remote Address: [::1]:8000
Referrer Policy: no-referrer-when-downgrade

我的 GET 请求在哪里?为什么我只看到我根本没有启动的选项?

来自angular的请求:

this.http.get<number>(this.route+'GPIO/'+gpio+'/value').subscribe(result => {
                resolve(result);
            })

我必须启用所有 headers 到 http 服务器:

def do_OPTIONS(self):
    self.send_response(200,"ok")
    self.send_header("Access-Control-Allow-Origin", "*")
    self.send_header("Access-Control-Allow-Methods", "*")
    self.send_header("Access-Control-Allow-Headers", "*")
    self.end_headers()