Angular 6 HttpClient和php后端CORS问题

时间:2019-03-07 02:24:55

标签: php angular cors angular6

从angular(6)前端访问php文件时,我始终会遇到cors和corb问题。

下面是代码:-

1-角度服务文件

httpOptions = {
headers: new HttpHeaders(
  { 'Content-Type': 'application/json' }
)

}

public getStudentData() {    
return this.http.get(this.url + '/getStudents.php', this.httpOptions);

}

2-这是调用服务的appcomponent-

ngOnInit() {

this.studentService.getStudentData().subscribe(
  (data) => {
    console.log("data: " + JSON.stringify(data));
    this.students = data;
    console.log("students record len: " + this.students.length);
  },
  (error) => console.log(error)
);

}

3-这是用于获取数据的php后端代码

    <?php 
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

include "db.php";

$sql = "SELECT * FROM student";
$result = $conn->query($sql);

$data = array();
if ($result->num_rows > 0) {

    foreach($result as $res){
        $data[] = $res;
    }

} 
$conn->close();
$data = json_encode($data);
echo $data;
//return $data;
?>

错误消息-这是错误消息

1-从起点“ http://scbo.byethost3.com/studentcrud//getStudents.php”到“ http://localhost:4200”的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control- Allow-Origin标头出现在所请求的资源上。

2- 消息:“ HTTP失败响应((未知URL):0未知错误)” 名称:“ HttpErrorResponse” 好的:错误 状态:0 statusText:“未知错误”

3- zone.js:3243跨域读取阻止(CORB)阻止了MIME类型为text / html的跨域响应http://scbo.byethost3.com/studentcrud//getStudents.php。有关更多详细信息,请参见https://www.chromestatus.com/feature/5629709824032768

注意-如果我将URL更改为本地系统,则此设置在本地主机中对我有效。

欢迎所有建议。

0 个答案:

没有答案