簡體   English   中英

jQuery ajax和跨域(CORS)和基本身份驗證

[英]jQuery ajax and cross domain (CORS) and Basic Authentication

我嘗試了建議的可能重復問題中的答案,但它們沒有改變結果。

我一直試圖通過ajax從本地PC上的客戶端(測試Chrome和IE)通過POST到遠程服務器的API,但沒有成功。 Ajax返回狀態為0的錯誤,服務器返回401。如果沒有基本身份驗證,我確認它可以工作。 但是,使用基本身份驗證后,它永遠無法工作。

客戶:

$.ajax({
    type : 'POST',
    url : 'http://api-url',
    data : data,
    success : function (response) {
        console.log(response);
    },
    error : function (xhr, status, error) {
        console.log(xhr);
        console.log(status);
        console.log(error);
    },
    beforeSend : function (xhr) {
        xhr.setRequestHeader('Authorization', 'Basic base64username:password');
    },
    xhrFields : {
        withCredentials : true
    }

服務器:

<?php
    header('Access-Control-Allow-Origin: http://localhost');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
    echo "ok";

誰能建議我可能會想念的東西。 我花了一天時間,但找不到任何可行的解決方案。

服務器是CentOS 6.7和Apache 2.2.15。

如果將Access-Control-Allow-Origin的遠程服務器設置僅設置為localhost,則它將僅適用於本地請求。 嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM