hoaaah / yii2-rest-api-template

REST API Template with Yii2
Other
33 stars 13 forks source link

Cors #4

Open Maclay74 opened 3 years ago

Maclay74 commented 3 years ago

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

hoaaah commented 3 years ago

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

Maclay74 commented 3 years ago

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.

hoaaah commented 3 years ago

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?

Maclay74 commented 3 years ago

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.