RESTFUL 创建资源成功之后为何是跳转而不是直接返回创建的值 [ 2.0 版本 ]
官方的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.
共 2 个回答
猫学乖
注册时间:2015-06-26
最后登录:2016-06-14
在线时长:9小时44分
最后登录:2016-06-14
在线时长:9小时44分
- 粉丝3
- 金钱223
- 威望20
- 积分513