laravel ajax"访问受限制的URI被拒绝"在邮政请求中

时间:2016-02-18 11:34:33

标签: php ajax http laravel-5

我正在使用laravel 5.2,并尝试向外部网站发布请求

我的ajax是:

$("#userLogin").click(function(){
    var usrEmail = $("#usr_email").val();
    var usrPassword = $("#usr_password").val();
    $.ajax({ 
        xhrFields: {
            withCredentials: true
        },
        url: 'http://username:password@website.com/APIs/public/login',
        data: {email: usrEmail, password:usrPassword},
        type: 'GET',
        error: function (request, error) {
            console.log(arguments);
        },
        success: function(data) {
            alert(data);
        }
    });
    event.preventDefault();
});

.htaccess档案中

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"  
    Header set Access-Control-Allow-Credentials true
</IfModule>


但是我收到了这个错误

"NS_ERROR_DOM_BAD_URI: Access to restricted URI denied"

1 个答案:

答案 0 :(得分:0)

您无法将ajax数据发送到http://username:password@website.com/APIs/public/login这样的网址。此网址似乎使用了基本身份验证。因此,您需要使用beforeSend回调来添加带有身份验证信息的HTTP标头:

var username = $("input#username").val();
var password = $("input#password").val();  

function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = btoa(tok);
  return "Basic " + hash;
}
$.ajax
  ({
    type: "GET",
    url: "http://website.com/APIs/public/login",
    dataType: 'json',
    async: false,
    data: '{YOUR DATA + LARAVEL _token}',
    beforeSend: function (xhr){ 
        xhr.setRequestHeader('Authorization', make_base_auth(username, password)); 
    },
    success: function (){
        ...
    }
});