Angular4无法向yii2应用程序发送发布请求

时间:2017-07-26 17:24:42

标签: javascript ajax angular http yii2

我使用此代码

this.http.post('http://l.example/angular/create/', {name: 'test'}).subscribe(
      (response) => console.log(response),
      (error) => console.log(error)
    );

将帖子请求发送到我的Yii2休息应用程序,但我在Chrome控制台上收到此错误,但是当我使用jquery $.post请求正常工作时

Erorr list

我的Yii2控制器代码

namespace app\controllers;

use yii\rest\ActiveController;

class AngularController extends ActiveController
{
    public $modelClass = 'app\models\Angular';

    public function beforeAction($action)
    {
        $this->enableCsrfValidation = false;


        return parent::beforeAction($action);
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();


        // add CORS filter
        $behaviors['corsFilter'] = [
            'class' => \yii\filters\Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
            ],

        ];
        $behaviors['contentNegotiator'] = [
            'class' => \yii\filters\ContentNegotiator::className(),
            'formats' => [
                'application/json' => \yii\web\Response::FORMAT_JSON,
            ],
        ];
        return $behaviors;
    }
}

注意

  • Angular 4 http.get正常工作并列出所有记录
  • 我使用Yii 2.0.14
  • Angular 4.3.1

我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

Yii中的预定义RESTful端点没有前导斜杠。

应该是:

'http://l.example/angular/create'

而不是

'http://l.example/angular/create/'