小编典典

飞行前响应中Access-Control-Allow-Headers不允许请求标头字段Access-Control-Allow-Headers

ajax

我正在尝试从跨域制作登录页面,但无法解决问题,错误是:

XMLHttpRequest无法加载http://localhost/testing/resp.php。在飞行前响应中,Access-
Control-Allow-Headers不允许请求标头字段Access-Control-Allow-Headers。

我的Javascript代码是:

$('#login').click(function(){

        var username = $('#uname').val();

        var password = $('#pass').val();

        var result = $('.result');

        result.text('loading....');



        if (username != '' && password !=''){

            var urltopass = 'action=login&username='+username+'&password='+password;

            $.ajax({

                type: 'POST',

                data: urltopass,

                headers: {"Access-Control-Allow-Headers": "Content-Type"},

                url: 'http://localhost/testing/resp.php',

                crossDomain: true,

                cache: false,

                success: function(responseText){

                    console.log(responseText);

                    if(responseText== "0"){

                        result.text('incorrect login information');

                    } else if (responseText == "1"){

                        window.location="http://localhost/testing/home.php";

                    } else{

                        alert('error in sql query \n' + responseText);

                    }

                }

            });

        } else return false;

    });

http://localhost/testing/resp.php的PHP代码:

<?php

    include "db.php"; //Connecting to database



    if (!isset($_SERVER['HTTP_ORIGIN'])) {

        echo "This is not cross-domain request";

    exit;

}

    header("Access-Control-Allow-Origin: *");

    header("Access-Control-Allow-Credentials: true");

    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");

    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

    header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies

    header("Content-Type: application/json; charset=utf-8");



    if (isset($_POST['action']) && $_POST['action'] == 'login'){

        $uname = $_POST['username'];

        $pass = $_POST['password'];



        $sql = "SELECT * FROM loginajax WHERE username='$uname' AND password='$pass'";



        $rs=$conn->query($sql);



        if (mysqli_num_rows($rs) <= 0){

            echo "0";

        } else {

            echo "1";

        }



    } else echo "this is not Login";



?>

阅读 679

收藏
2020-07-26

共1个答案

小编典典

删除此:

headers: {"Access-Control-Allow-Headers": "Content-Type"},

从您的jQuery.ajax调用中。

服务器用Access-Control-Allow-Headers头响应,客户端不将其发送到服务器。

客户端发送Access-Control-Request-Headers请求允许某些标头的请求,服务器以响应并Access-Control-Allow- Headers列出其允许的实际标头。客户端不会要求允许哪些标头。

2020-07-26