yii2-rest-api-template icon indicating copy to clipboard operation
yii2-rest-api-template copied to clipboard

Cors

Open Maclay74 opened this issue 4 years ago • 4 comments

It would be great to have them out of the box, because without headers it doesn't work at all.

Maclay74 avatar Feb 20 '21 22:02 Maclay74

I don't get it? Please elaborate the use case.

hoaaah avatar Feb 23 '21 15:02 hoaaah

Sure!

When you use API for a single-page application, like created on react or something, you usually locate them on different domains. Moreover, during development they can be both on localhost but on different ports.

And by default, cors wouldn't allow to make requests from frontend to backend, if backend doesn't provide client with special headers.

It's only a browser's thing, mobile apps don't rely on cors.

So, my workaround was to add them like that

 $behaviors['corsFilter'] = [
            'class' => '\yii\filters\Cors',
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
            ],
        ];

But I created a BaseController class and extend it everytime instaed of ActiveController, because my application is built this way.

Maclay74 avatar Feb 23 '21 20:02 Maclay74

Oh right. I'm using this template for mobile device and web services. I still can't get the best approach for this feature.

Will all controller use this? If we add corsFilter to BehaviorsFromParamsHelper then this template will be difficult to extend. It might be enough to add this case in to documentation, including the option to use a modified BaseController as your example.

Do you have a better idea?

hoaaah avatar Mar 03 '21 15:03 hoaaah

I use BaseController with behaviours, but you can just mention this part in README, so user will handle it somehow. Just an advice with code sample would be great, we deal with developers, anyway.

Maclay74 avatar Mar 03 '21 19:03 Maclay74