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
要求工作
我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
哪裏是我的錯?
'http.post'需要第三個參數'options'。這包括標題。你可能必須通過這個。 – ecain
@ecain 我使用這個 'const header = new Headers({'Content-Type':'application/json','Accept':'application/json'}); const options = new RequestOptions({headers:header});' 但不工作 – Morteza
什麼是錯誤? – ecain