REST API error “CORS preflight channel did not succeed”

你。 提交于 2019-12-10 23:43:24

问题


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?


回答1:


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'],
            ],
        ],
    ];
}



回答2:


My short solution:

  • On server side:
    npm install cors
    

    add app.use(cors({origin: '*'})); before all route definitions

  • On client side: do everything normally
    $http.get('http://localhost:36912/api/permissions').then(function (response) {
       console.log(response);
    })
    .catch(function (error) {
       console.error('Status code: ' + error.status);
       console.error('Error message: ' + error.data);
    });
    


    来源:https://stackoverflow.com/questions/38195794/rest-api-error-cors-preflight-channel-did-not-succeed

  • 易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!