Access-Control-Allow-Origin Multiple Origin Domains?

前端 未结 30 2500
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 07:08

Is there a way to allow multiple cross-domains using the Access-Control-Allow-Origin header?

I\'m aware of the *, but it is too open. I rea

30条回答
  •  半阙折子戏
    2020-11-21 07:14

    Only a single origin can be specified for the Access-Control-Allow-Origin header. But you can set the origin in your response according to the request. Also don't forget to set the Vary header. In PHP I would do the following:

        /**
         * Enable CORS for the passed origins.
         * Adds the Access-Control-Allow-Origin header to the response with the origin that matched the one in the request.
         * @param array $origins
         * @return string|null returns the matched origin or null
         */
        function allowOrigins($origins)
        {
            $val = $_SERVER['HTTP_ORIGIN'] ?? null;
            if (in_array($val, $origins, true)) {
                header('Access-Control-Allow-Origin: '.$val);
                header('Vary: Origin');
    
                return $val;
            }
    
            return null;
        }
    
      if (allowOrigins(['http://localhost', 'https://localhost'])) {
          echo your response here, e.g. token
      }
    

提交回复
热议问题