最近一直出现这样的错误,一直在查找原因,偶然看到一篇解决的文章,分享给大家看看。

第一种解决办法是关闭Csrf

public function init(){  $this->enableCsrfValidation = false;}

第二种解决办法是在form表单中加入隐藏域

<input name="_csrf" type="hidden" id="_csrf" value="<?= Yii::$app->request->csrfToken ?>">

第三种解决办法是在AJAX中加入_csrf字段

var csrfToken = $("meta[name="csrf-token"]").attr("content");$.ajax({ type: "POST", url: url, data: {_csrf:csrfToken}, success: success, dataType: dataType});

Yii这个匹配的过程和Yii::$app->request->csrfToken 这个值存储位置说明:

存储位置

  protected function createCsrfCookie($token)  {    $options = $this->csrfCookie;    $options["name"] = $this->csrfParam;    $options["value"] = $token;    return new Cookie($options);  }

校验方法

  public function validateCsrfToken($token = null)  {    $method = $this->getMethod();    // only validate CSRF token on non-"safe" methods http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1    if (!$this->enableCsrfValidation || in_array($method, ["GET", "HEAD", "OPTIONS"], true)) {      return true;    }    $trueToken = $this->loadCsrfToken();    if ($token !== null) {      return $this->validateCsrfTokenInternal($token, $trueToken);    } else {      return $this->validateCsrfTokenInternal($this->getBodyParam($this->csrfParam), $trueToken)        || $this->validateCsrfTokenInternal($this->getCsrfTokenFromHeader(), $trueToken);    }  }

以上所述就是本文的全部内容了,希望大家能够喜欢。