使用$response->withHeaders()设置跨域时遇到一个问题

lethe

跨域部分代码

        $response->withHeaders([
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Headers' => '*',
            'Access-Control-Allow-Methods' => 'GET,POST,PUT,DELETE,OPTIONS',
        ]);

url第一次访问正常
使用$response->getHeaders()获取所有header为:

array(6) {
  ["Server"]=>
  string(11) "ParentAdmin"
  ["content-type"]=>
  string(31) "application/json; charset=utf-8"
  ["Access-Control-Allow-Origin"]=>
  string(1) "*"
  ["Access-Control-Allow-Credentials"]=>
  string(4) "true"
  ["Access-Control-Allow-Headers"]=>
  string(1) "*"
  ["Access-Control-Allow-Methods"]=>
  string(27) "GET,POST,PUT,DELETE,OPTIONS"
}

再次访问url的时候就变成了

array(6) {
  ["Server"]=>
  string(11) "ParentAdmin"
  ["content-type"]=>
  string(31) "application/json; charset=utf-8"
  ["Access-Control-Allow-Origin"]=>
  array(2) {
    [0]=>
    string(1) "*"
    [1]=>
    string(1) "*"
  }
  ["Access-Control-Allow-Credentials"]=>
  array(2) {
    [0]=>
    string(4) "true"
    [1]=>
    string(4) "true"
  }
  ["Access-Control-Allow-Headers"]=>
  array(2) {
    [0]=>
    string(1) "*"
    [1]=>
    string(1) "*"
  }
  ["Access-Control-Allow-Methods"]=>
  array(2) {
    [0]=>
    string(27) "GET,POST,PUT,DELETE,OPTIONS"
    [1]=>
    string(27) "GET,POST,PUT,DELETE,OPTIONS"
  }
}

同时浏览器就报跨域问题了

这样设置就没问题了

        $response->header('Access-Control-Allow-Origin','*');
        $response->header('Access-Control-Allow-Credentials','true');
        $response->header('Access-Control-Allow-Headers','*');
        $response->header('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS');
987 1 0
1个回答

xiuwang

$response哪来的,完整点代码呢

  • 暂无评论
年代过于久远,无法发表回答
×
🔝