Angular4不行发送POST请求yii2应用
问题描述:
我使用此代码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
哪里是我的错?
答
Yii中预定义的RESTful端点没有前导斜杠。
它应该是:
'http://l.example/angular/create'
,而不是
'http://l.example/angular/create/'
'http.post'需要第三个参数'options'。这包括标题。你可能必须通过这个。 – ecain
@ecain 我使用这个 'const header = new Headers({'Content-Type':'application/json','Accept':'application/json'}); const options = new RequestOptions({headers:header});' 但不工作 – Morteza
什么是错误? – ecain