Prakash Baskaran Prakash Baskaran - 2 months ago 43
reST (reStructuredText) Question

REST API error "CORS preflight channel did not succeed"

I created a RESTapi to insert data into my databse, It's working perfectly on POSTMAN extension, but I'm getting an error on angularjs http post method.

My Restapi code is created in yii2 framework. My code is below,

public function actionNew()
{

$model = new Apieducation();

$user_id = $_REQUEST['user_id'];

$education = $_REQUEST['education'];

$passing_year = $_REQUEST['passing_year'];

$institute = $_REQUEST['institute'];


//$model->attributes=$params;
$model->user_id = $user_id;
$model->education = $education;
$model->passing_year = $passing_year;
$model->institute = $institute;


if ($model->save()) {

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With,content-type");
echo json_encode(array('status'=>'1','data'=>$model->attributes),JSON_PRETTY_PRINT);
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
}
else
{

$jobs[] = 'failed';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With,content-type");
echo json_encode(array('status'=>'1','data'=>array_filter($jobs)),JSON_PRETTY_PRINT);
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

}

}


And My Angularjs function code is,

$scope.educationcreate = function() {

var data = $.param({
user_id: $scope.data.user_id,
education: $scope.data.education,
passing_year: $scope.data.passing_year,
institute: $scope.data.institute
});

var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
};

$http.post('http://localhost/basic/web/index.php?r=apieducation/new', data, config)
.success(function(data, status, headers, config) {

alert('Successfully');
})
.error(function(data, status, headers, config) {
alert("ERROR");
});

};


I got console error,

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/basic/web/index.php?r=apieducation/new. (Reason: CORS preflight channel did not succeed).


How can I solve it?

Answer

Using the Cors filter to solve this error,

public function behaviors()
{
    return [
        'corsFilter' => [
            'class' => Cors::className(),
            'cors' => [
                // restrict access to
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'GET'],
                // Allow only POST and PUT methods
                'Access-Control-Request-Headers' => [' X-Requested-With'],
                // Allow only headers 'X-Wsse'
                'Access-Control-Allow-Credentials' => true,
                // Allow OPTIONS caching
                'Access-Control-Max-Age' => 3600,
                // Allow the X-Pagination-Current-Page header to be exposed to the browser.
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ],
    ];
}
Comments