XMLHttpRequest changes POST to OPTION

前端 未结 4 614
难免孤独
难免孤独 2020-12-07 20:23

i have this code:

net.requestXHR = function() {
    this.xhr = null;
    if(window.XMLHttpRequest === undefined) {
        window.XMLHttpRequest = function()         


        
4条回答
  •  感动是毒
    2020-12-07 20:43

    As others have pointed out, this is a CORS thing.

    This is how to handle it in NGINX (based on this source):

    location / {
        if ($request_method = OPTIONS ) {
            add_header Access-Control-Allow-Origin "http://example.com";
            add_header Access-Control-Allow-Methods "GET, OPTIONS";
            add_header Access-Control-Allow-Headers "Authorization";
            add_header Access-Control-Allow-Credentials "true";
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            return 200;
        }
    }
    

    If you want to allow CORS requests from any origin, replace,

    add_header Access-Control-Allow-Origin "http://example.com";
    

    with

    add_header Access-Control-Allow-Origin "*";
    

    If you don't use authorization, you won't need this bit:

    add_header Access-Control-Allow-Headers "Authorization";
    add_header Access-Control-Allow-Credentials "true";
    

    For the API I'm developing I needed to whitelist 3 request methods: GET, POST and OPTIONS, and an X-App-Id header, so this us what I ended up doing:

    if ($request_method = OPTIONS ) {
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
        add_header Access-Control-Allow-Headers "X-App-Id";
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        return 200;
    }
    

提交回复
热议问题