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

Implementing Cross-Origin Resource Sharing in Yii 2.0 RESTful APIs

Requesting the API http://api.pcs.wjdev.chinamcloud.cn/v1/plan-tasks/274?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=b26398238620e8cd15b0155cd7aee9b2 from the domain http://editorweb.wjdev.chinamcloud.cn returned a 404 response, with the error that the "Access-Control-Allow-Origin" header is not present on the requested resource.

1. Requesting the API http://api.pcs.wjdev.chinamcloud.cn/v1/plan-tasks/274?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=b26398238620e8cd15b0155cd7aee9b2 from the domain http://editorweb.wjdev.chinamcloud.cn returned a 404 response, with the error that the “Access-Control-Allow-Origin” header is not present on the requested resource. See Figure 1.

Requesting the API http://api.pcs.wjdev.chinamcloud.cn/v1/plan-tasks/274?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=b26398238620e8cd15b0155cd7aee9b2 from the domain http://editorweb.wjdev.chinamcloud.cn returned a 404 response, with the error that the "Access-Control-Allow-Origin" header is not present on the requested resource.
Figure 1
Plaintext
OPTIONS http://api.pcs.wjdev.chinamcloud.cn/v1/plan-tasks/274?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=b26398238620e8cd15b0155cd7aee9b2 404 (Not Found) Access to fetch at 'http://api.pcs.wjdev.chinamcloud.cn/v1/plan-tasks/274?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=b26398238620e8cd15b0155cd7aee9b2' from origin 'http://editorweb.wjdev.chinamcloud.cn' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

2. I decided to first build a frontend Ajax request example locally.

JavaScript
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3E%0A%20%20%20%20%24.post(%22http%3A%2F%2Fapi.pcs-api.localhost%2Fv1%2Fplan-tasks%2F88%3Flogin_id%3D2e368664c41b8bf511bcc9c65d86dbc3%26login_tid%3Db26398238620e8cd15b0155cd7aee9b2%22%2C%20%7B%7D%2C%0A%20%20%20%20%20%20%20%20function(data)%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20console.log(data.code)%3B%0A%20%20%20%20%20%20%20%20%7D%2C%20%22json%22)%3B%0A%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
 

3. The POST request returned a 200 response, but there was no response data. See Figure 2.

The POST request returned a 200 response, but there was no response data.
Figure 2
Plaintext
Access to XMLHttpRequest at 'http://api.pcs-api.localhost/v1/plan-tasks/88?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=b26398238620e8cd15b0155cd7aee9b2' from origin 'http://www.pcs-api.localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
jquery.js:9837 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://api.pcs-api.localhost/v1/plan-tasks/88?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=b26398238620e8cd15b0155cd7aee9b2 with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.

4. Referring to the Cross-Origin Resource Sharing (CORS) mechanism at https://www.yiiframework.com/doc/guide/2.0/zh-cn/structure-filters#cors , I added the Cross-Origin Resource Sharing filter to the controller.

PHP
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        // remove authentication filter
        $auth = $behaviors['authenticator'];
        unset($behaviors['authenticator']);

        // add CORS filter
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
        ];

        // re-add authentication filter
        $behaviors['authenticator'] = $auth;
        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }

5. Upon making the POST request again, the response was 200, and the console in the browser successfully output the code from the response data. See Figure 3 and Figure 4.

Upon making the POST request again, the response was 200, and the console in the browser successfully output the code from the response data.
Figure 3

 

Upon making the POST request again, the response was 200, and response data was present.
Figure 4

6. Therefore, the editor’s frontend needed to be adjusted to match the Ajax request example. The Content-Type value was changed from application/json to application/x-www-form-urlencoded. Finally, the server received the request data and returned a 200 response. The log data for the request returning 200 is shown. See Figure 5.

Therefore, the editor's frontend needed to be adjusted to match the Ajax request example. The Content-Type value was changed from application/json to application/x-www-form-urlencoded. Finally, the server received the request data and returned a 200 response.
Figure 5
Plaintext
[
    'url' => '/v1/plan-tasks/274?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=82c3f78c73c01c92b41a90f6b8b88efd',
    'request_query_params' => [
        'id' => '274',
        'login_id' => '2e368664c41b8bf511bcc9c65d86dbc3',
        'login_tid' => '82c3f78c73c01c92b41a90f6b8b88efd',
    ],
    'request_body_params' => [
        '{"id":274,"queryParam":"eyJ0YXNrSWQiOjI3NCwiY2FsbGJhY2tGbGFnIjoiWSIsImNhbGxiYWNrVXJsIjoiaHR0cDovL2FwaS5wY3Mud2pkZXYuY2hpbmFtY2xvdWQuY24vdjEvcGxhbi10YXNrLXJlc291cmNlcy9jYWxsYmFjaz9sb2dpbl9pZD0yZTM2ODY2NGM0MWI4YmY1MTFiY2M5YzY1ZDg2ZGJjMyZsb2dpbl90aWQ9ODJjM2Y3OGM3M2MwMWM5MmI0MWE5MGY2YjhiODhlZmQiLCJlZGl0b3JfdHlwZSI6IjIiLCJlZGl0b3JfdGl0bGUiOiLmkrDlhpnkvpvnqL8tMjAyMDA1MjgtMiIsImVkaXRvcl9pZCI6Mjc0LCJlZGl0b3JfY2FsbGJhY2tfdXJsIjoiaHR0cDovL2FwaS5wY3Mud2pkZXYuY2hpbmFtY2xvdWQuY24vdjEvcGxhbi10YXNrcy8yNzQ/bG9naW5faWQ9MmUzNjg2NjRjNDFiOGJmNTExYmNjOWM2NWQ4NmRiYzMmbG9naW5fdGlkPTgyYzNmNzhjNzNjMDFjOTJiNDFhOTBmNmI4Yjg4ZWZkIiwiZGF0YSI6eyJzb3VyY2UiOiJjaGluYW1jbG91ZF9zY21zIiwiY3VycmVudF9zdGVwX2NvZGUiOiJ3cml0ZV9mZWVkIiwib2JqZWN0X3R5cGUiOiJmZWVkIiwiYXJ0aWNsZV90eXBlX2lkIjoxfX0' => '"}',
    ],
    'user_id' => '3',
    '$_SERVER' => [
        'HTTP_ACCEPT_LANGUAGE' => 'zh-CN,zh;q=0.9',
        'HTTP_ACCEPT' => 'application/json,text/plain, */*',
        'HTTP_HOST' => 'api.pcs.wjdev.chinamcloud.cn',
        'REMOTE_ADDR' => '10.42.22.22',
        'REQUEST_URI' => '/v1/plan-tasks/274?login_id=2e368664c41b8bf511bcc9c65d86dbc3&login_tid=82c3f78c73c01c92b41a90f6b8b88efd',
        'REQUEST_METHOD' => 'POST',
        'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
    ],
]

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

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

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

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

关于我  ·  GitHub  ·  邮件联系