REST API错误" CORS预检频道未成功"

时间:2016-07-05 05:31:49

标签: angularjs api rest yii2

我创建了一个RESTapi来将数据插入到我的数据库中,它在POSTMAN扩展上完美运行,但我在angularjs http post方法上收到错误。

我的Restapi代码是在yii2框架中创建的。我的代码如下,

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;

  }

}

我的Angularjs功能代码是,

$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");
        });

      };

我收到了控制台错误,

  

阻止跨源请求:同源策略禁止读取   远程资源在   http://localhost/basic/web/index.php?r=apieducation/new。 (原因:CORS   预检频道没有成功。)

我该如何解决?

2 个答案:

答案 0 :(得分:0)

使用Cors过滤器来解决此错误,

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

答案 1 :(得分:0)

我的简短解决方案:

  • 在服务器端:

    npm install cors
    

    在所有路线定义

    之前添加app.use(cors({origin: '*'}));

  • 在客户端: 通常做一切

    $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);
    });