Yii2 CORS插入两个记录

I am building an API with Yii2 and have enabled the CORS filter to handle requests from a web frontend which is working.

However because of the pre-flight OPTIONS request and then the real POST request I am getting two records added to the database, one for each request. I would have thought that Yii should accept the OPTIONS request, return the correct headers and then exit. Why does it actually process the full request?

I am working around this for now by adding this to the top of the controller action:

if(Yii::$app->request->getMethod() == 'OPTIONS') {
    return;
}

Is that the best approach or am I missing something?

That should be wrong because a browser need the options response to know the allowed list of verbs he can send. Otherwise a 401 error may be raised. Its source code can be seen here:

class OptionsAction extends \yii\base\Action
{
    public $collectionOptions = ['GET', 'POST', 'HEAD', 'OPTIONS'];
    public $resourceOptions = ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];

    public function run($id = null)
    {
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
            Yii::$app->getResponse()->setStatusCode(405);
        }
        $options = $id === null ? $this->collectionOptions : $this->resourceOptions;
        Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $options));
    }
}

And that is all what it does: sending a list of allowed verbs within a response headers.

Maybe the POST request has been sent twice from client script due to unexpected responses. Try to apply the answer I posted in your other question instead. I think it will also solve this:

Yii2 CORS with Auth not working for non CRUD actions.