2017-07-26 20 views
1

我使用此代碼Angular4不行發送POST請求yii2應用

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

到POST請求發送到我的Yii2其他應用程序,但我得到的鉻控制檯上的錯誤,但是當我正確使用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; 
    } 
} 

注意

  • 角4 http.get正常工作,並列出所有記錄
  • 我使用的Yii 2.0.14
  • 角4.3.1

哪裏是我的錯?

+0

'http.post'需要第三個參數'options'。這包括標題。你可能必須通過這個。 – ecain

+0

@ecain 我使用這個 'const header = new Headers({'Content-Type':'application/json','Accept':'application/json'}); const options = new RequestOptions({headers:header});' 但不工作 – Morteza

+0

什麼是錯誤? – ecain

回答

0

Yii中預定義的RESTful端點沒有前導斜槓。

它應該是:

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

,而不是

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