gpt4 book ai didi

angularjs - REST API 错误 "CORS preflight channel did not succeed"

转载 作者:行者123 更新时间:2023-12-04 03:21:16 35 4
gpt4 key购买 nike

我创建了一个 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");
});

};

我收到控制台错误,

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).

我该如何解决?

最佳答案

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

关于angularjs - REST API 错误 "CORS preflight channel did not succeed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38195794/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com