没有不值得去解决的问题,也没有不值得去学习的技术!

When a Server Exception Occurs in Yii2, It Does Not Return a 500 but Shows a CORS Error in the Browser

In Yii2, when a server-side exception occurs, it does not return a 500 response. Instead, the browser reports a CORS error, which causes the frontend to hang in a loading state from the user's perspective. The console displays the following message

1. In Yii2, when a server-side exception occurs, it does not return a 500 response. Instead, the browser reports a CORS error, which causes the frontend to hang in a loading state from the user’s perspective. The console displays the following message, as shown in Figure 1.

In Yii2, when a server-side exception occurs, it does not return a 500 response. Instead, the browser reports a CORS error, which causes the frontend to hang in a loading state from the user's perspective. The console displays the following message
Figure 1
Plaintext

Access to XMLHttpRequest at 'https://api.apply.local/convention-free-field/get-search-condition-fields-by-convention-id' from origin 'https://console.apply.local' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'https://console.apply.local, *', but only one is allowed.

2. The current logic is that in the browser, the frontend requests the backend API via JS. Therefore, to prevent CORS issues, the backend implementation is as follows.

PHP

public static function setAllowOrigin()
{
	$httpOrigin = $_SERVER['HTTP_ORIGIN'] ?? '';
	Yii::debug('OPTION CHECK: ' . $httpOrigin);
	if (
		in_array($httpOrigin, [
		//
		'http://console.apply.local',
		'https://console.apply.local',
		'http://tougao.apply.local',
		'https://tougao.apply.local',
		'http://apply.local',
		'https://apply.local',
		'http://official.local',
		'http://localhost:8080',
		'http://localhost:8081',
		'http://localhost:8082',
		'http://localhost:8083',
		'http://localhost:8084',
		//正式域名
		])
	) {
		\Yii::$app->response->headers->add('Access-Control-Allow-Origin', $httpOrigin);
		\Yii::$app->response->headers->add('Access-Control-Allow-Headers', '*');
	}
}

self::setAllowOrigin();

3. A close analysis of the request response headers reveals that access-control-allow-origin: * overrides the access-control-allow-origin: https://console.apply.local set in the setAllowOrigin method. As shown in Figure 2.

A close analysis of the request response headers reveals that access-control-allow-origin: * overrides the access-control-allow-origin: https://console.apply.local set in the setAllowOrigin method
Figure 2

4. I decided to comment out all instances of the setAllowOrigin method from step 2 to avoid leaving a large number of commented-out self::setAllowOrigin(); calls.

PHP


    public static function setAllowOrigin()
    {
//        $httpOrigin = $_SERVER['HTTP_ORIGIN'] ?? '';
//        Yii::debug('OPTION CHECK: ' . $httpOrigin);
//        if (
//            in_array($httpOrigin, [
//            //
//            'http://console.apply.local',
//            'https://console.apply.local',
//            'http://tougao.apply.local',
//            'https://tougao.apply.local',
//            'http://apply.local',
//            'https://apply.local',
//            'http://official.local',
//            'http://localhost:8080',
//            'http://localhost:8081',
//            'http://localhost:8082',
//            'http://localhost:8083',
//            'http://localhost:8084',
//            //正式域名
//            ])
//        ) {
//            \Yii::$app->response->headers->add('Access-Control-Allow-Origin', $httpOrigin);
//            \Yii::$app->response->headers->add('Access-Control-Allow-Headers', '*');
//        }
    }

self::setAllowOrigin();

5. Centralize the configuration in the base class of all API controllers.

PHP


    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => [
                'Origin' => [
                    //
                    'http://console.apply.local',
                    'https://console.apply.local',
                    'http://tougao.apply.local',
                    'https://tougao.apply.local',
                    'http://apply.local',
                    'https://apply.local',
                    'http://official.local',
                    'http://localhost:8080',
                    'http://localhost:8081',
                    'http://localhost:8082',
                    'http://localhost:8083',
                    'http://localhost:8084',
                    //正式域名
                ],
                'Access-Control-Allow-Headers' => ['*'],
            ],
        ];
        return $behaviors;
    }

6. When a server-side exception occurs, the browser no longer reports a CORS error. Instead, it responds normally as expected. As shown in Figure 3.

When a server-side exception occurs, the browser no longer reports a CORS error. Instead, it responds normally as expected
Figure 3

7. Checking the response headers shows access-control-allow-origin: https://console.apply.local. This matches expectations. As shown in Figure 4.

Checking the response headers shows access-control-allow-origin: https://console.apply.local. This matches expectations
Figure 4

8. When the frontend URL is not in the Origin configuration, it reports a CORS error, which is the expected behavior.

Plaintext

Access to XMLHttpRequest at 'https://api.apply.local/convention-free-field/get-search-condition-fields-by-convention-id' from origin 'https://console.apply.local' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系