Deadly CORS when http://localhost is the origin

后端 未结 9 1309
迷失自我
迷失自我 2020-11-22 00:54

I am stuck with this CORS problem, even though I set the server (nginx/node.js) with the appropriate headers.

I can see in Chrome Network pane -> Response Headers:

相关标签:
9条回答
  • 2020-11-22 01:38

    The real problem is that if we set -Allow- for all request (OPTIONS & POST), Chrome will cancel it. The following code works for me with POST to LocalHost with Chrome

    <?php
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        //header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Credentials: true');    
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
    }   
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    } 
    ?>
    
    0 讨论(0)
  • 2020-11-22 01:40

    Chrome will make requests with CORS from a localhost origin just fine. This isn't a problem with Chrome.

    The reason you can't load http://stackoverflow.com is that the Access-Control-Allow-Origin headers weren't allowing your localhost origin.

    0 讨论(0)
  • 2020-11-22 01:43

    Chrome does not support localhost for CORS requests (a bug opened in 2010, marked WontFix in 2014).

    To get around this you can use a domain like lvh.me (which points at 127.0.0.1 just like localhost) or start chrome with the --disable-web-security flag (assuming you're just testing).

    0 讨论(0)
提交回复
热议问题