2016-05-04 15:51:34 3722次浏览 2条回答 0 悬赏 10 金钱

官方的CreateAction中在创建代码

   /**
     * Creates a new model.
     * @return \yii\db\ActiveRecordInterface the model newly created
     * @throws ServerErrorHttpException if there is any error when creating the model
     */
    public function run()
    {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }

        /* @var $model \yii\db\ActiveRecord */
        $model = new $this->modelClass([
            'scenario' => $this->scenario,
        ]);

        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
        if ($model->save()) {
            $response = Yii::$app->getResponse();
            $response->setStatusCode(201);
            $id = implode(',', array_values($model->getPrimaryKey(true)));
            $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));
        } elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
        }

        return $model;
    }

可以看到, 在model创建成功之后 进行了一次页面跳转, 导致ajax跨域请求创建成功, 但是收到了一个页面跳转的错误, 除了复写这个CreateAction之外有没有别的优雅一些的办法?
控制台里面是这样报错的

XMLHttpRequest cannot load http://xxxxx/api/v1/data/create. The request was redirected to 'http://xxxxx/api/v1/data/2', which is disallowed for cross-origin requests that require preflight.
  • 回答于 2016-05-05 12:53 举报

    个人感觉yii\rest\ActiveController的那一堆预先写好的action有点鸡肋。我都是直接从\yii\rest\Controller派生控制器,自己写接口更方便。

    1 条回复
    回复于 2016-05-05 16:08 回复

    我现在也是重写了yii\rest\ActiveController 还有那些不符合我需求的action

  • 回答于 2016-05-06 14:36 举报

    RESTFul为什么创建之后就跳转?因为这本身就是RESTFul设计目的,它需要告诉客户端如何处理下步操作。

您需要登录后才可以回答。登录 | 立即注册
猫学乖
主管

猫学乖

注册时间:2015-06-26
最后登录:2016-06-14
在线时长:9小时44分
  • 粉丝3
  • 金钱223
  • 威望20
  • 积分513

热门问题