weixin_33699914 2016-03-01 05:07 采纳率: 0%
浏览 37

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?

  • 写回答

1条回答 默认 最新

  • larry*wei 2016-03-30 08:45
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记