簡體   English   中英

Yii2 錯誤請求 (#400)

[英]Yii2 Bad Request (#400)

在我的系統中添加此代碼后,我試圖登錄我的系統它給了我錯誤的請求方法因為我不想禁用 CSrf 方法這是在 layouts/main.php

<div class="wrap">
    <?php
    NavBar::begin([
        'brandLabel' => Yii::$app->name,
        'brandUrl' => Yii::$app->homeUrl,

    ]);
    $menuItems = [
        ['label' => 'Home', 'url' => ['/site/index']],
    ];
    if (Yii::$app->user->isGuest) {
        $menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
    } else {
        $menuItems[] = [
                'label' => 'logout('.Yii::$app->user->user->identity->username.')',
                 'url' =>['/site/logout'],
                 'linkOptions' =>[
                        'data-method'=> 'post'
                ]
        ];
    }

然后是 SiteController.php

public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $this->layout = 'blank';

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

確保你的布局文件中有這個:

<?php $this->registerCsrfMetaTags(); ?>

而且您的表單中還需要一個 csrfInput。 如果您沒有使用ActiveForm生成表單,則必須手動添加,例如:

<input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />

csrfParam 默認為“_csrf”,但可以這樣使用。 您可能希望將來重命名它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM