M
M
MikUrrey2021-04-19 14:24:39
Yii
MikUrrey, 2021-04-19 14:24:39

How to properly configure CORS in the Yii2 REST API?

The module processes REST requests, each of its controllers has a configured `corsFilter` behavior.
Everything works fine until some error occurs (whether it's a 404 or a bug in the code).
Then the request does not reach the controller (?) and `corsFilter` does not work. Bottom line: CORS error in the browser and the absence of any response from the server for adequate processing. `corsFilter` specified in the module does not change the picture in any way.
How to properly configure CORS in Yii2 so that the setting will work for any error at the module level?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MikUrrey, 2021-04-28
@MikUrrey

According to the tradition that has developed here, I myself answer my own question.
For CORS to work properly, you need
1) corsFilter in behaviors should be at the very top;
2) make sure that everything you need is allowed in it, including the headers that you send to the server;
3) in actions you need to add:

'options' => [
  'class' => \yii\rest\OptionsAction::class,
],

4) checkAccess in the options action should not appear, this endpoint should always be available;
5) if a special route is specified in the configuration using UrlRule with verbs, then OPTIONS must be added to the verb.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question