使用navigation.sendBeacon发送application / json数据,预检成功但不发布

时间:2017-05-23 16:09:30

标签: javascript node.js express

使用sendBeacon将数据发布到服务器时遇到问题。

它适用于Chrome(因为Chrome似乎跳过预检)但在Firefox中,预检(OPTIONS)与请求标头一起发送:

b

来自服务器的响应是200:

b = 0
last = int(input()) 

while True:
    new = int(input())
    if (new == -1) or (last == -1):
        break
    elif new > last :
        if b == 2: # this has been descending until now
            b = 0 # neither ascending nor descending
            break
        b = 1
    elif new < last:
        if b == 1: # this has been ascending until now
            b = 0
            break
        b = 2
    else: # when two adjacent values are equal, this order is neither ascending, nor descending
        b = 0
        break
    last = new

if not b:
    print("Neither ascending, nor descending")
elif b == 1:
    print ('ascending')
elif b == 2:
    print ('descending')
else:
    print("This is odd, we shouldn't have got here...")

客户端代码:

Host: example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) 
Gecko/20100101 Firefox/53.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://example.com
Connection: keep-alive

服务器正在使用来自npm的CORS包:

Date: Tue, 23 May 2017 15:53:56 GMT
Content-Type: text/html; charset=utf-8
Set-Cookie: __cfduid=df2864c1da991df4abc28d3e73db7ab8f1495554836;expires=Wed, 23-May-18 15:53:56 GMT; path=/; domain=.medialaben.no;HttpOnly
X-Powered-By: Express
Access-Control-Allow-Origin: *
access-control-allow-credentials: true
access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
access-control-allow-headers: content-type,Authorization,Origin,Connection,Accept
Allow: POST
Server: cloudflare-nginx
cf-ray: 363930e0688e3cfb-CPH
Content-Encoding: gzip
X-Firefox-Spdy: h2

编辑:错误讯息为let inscreenCollection = [someObject, someObject2] let headers = { type: "application/json" }; let blob = new Blob([JSON.stringify(inscreenCollection)], headers); navigator.sendBeacon(URL, blob);

任何人都知道这里的问题是什么?

1 个答案:

答案 0 :(得分:1)

信标会under some circumstances发送凭据,因此您要避免这些情况或避免使用来源*。

  

sendBeacon发起的请求受以下属性约束:

     

如果有效负载是application / x-www-form-urlencoded,multipart / form-data或text / plain之一,那么请求是一个简单的请求,不需要额外的CORS预检;与脚本化的form-post或XHR / fetch相同。

     

否则,如果有效负载是Blob并且生成的Content-Type不是简单的标头,则进行CORS预检,并且服务器需要首先通过返回适当的CORS标头集来允许此类请求( Access-Control-Allow-Credentials ,Access-Control-Allow-Origin,Access-Control-Allow-Headers);与XHR / fetch相同。