我正在尝试使用ionic 2和angular 2进行登录访问。每当我按下正确的详细信息时,我都会收到此错误
XMLHttpRequest cannot load http://adirzoari.16mb.com/newapi.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.'
我也在网站上阅读了一些类似的问题,仍然没有得到任何解决方案。
这是我的登录php文件
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("mysql.hostinger.co.uk", "a", "1234", "appd");
//http://stackoverflow.com/questions/18382740/cors-not-working-php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
//http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$username = $request->username;
$password = $request->password;
$data = array();
if ($password != "" && $username != "") {
//echo "Server returns: " . $username . "Password is :" . $password;
/*$arr=array();
$st="select * from subnews order by SubID desc limit 10";
$qr=$conn->query($st);
while($row=$qr->fetch_assoc()){
$arr[]=$row;
}
echo json_encode($arr);*/
$sel="SELECT id FROM users WHERE username='$username' AND password='$password'";
$result=$conn->query($sel);
$numrow=$result->num_rows;
if($numrow == 1){
include 'tokengenerate.php';
$token=generateRandomString();
$update="update users set token='$token' where username='$username' AND password='$password'";
$qr=$conn->query($update);
if($qr){
$sel="SELECT id FROM users WHERE username='$username' AND password='$password'";
$query=$conn->query($sel);
while($row=$query->fetch_assoc(){
$data[]=array(
"name"->$row['username'],
"token"->$row['token']
);
echo json_encode($data);
}
}
}
}
else {
header('HTTP/1.1 401 Unauthorized', true, 401);
}
}
else {
echo "Not called properly with username parameter!";
}
?>
当您从域中将XmlHttpRequest发送到另一个域时,可能会导致此问题,并且出于安全目的,浏览器因交叉源而阻塞。
如果您没有向非安全网址提出请求,请向另一个支票提出请求,例如:从http url到https的请求,这也可能导致它。