如何在我的ASP.NET Button OnClientClick事件中包含Access-Control-Allow-Origin标头?

时间:2019-02-15 05:31:37

标签: javascript asp.net cors dotnetnuke

我已经编写了单击ASP.NET按钮时调用的以下Javascript:

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined") {
        xhr = new XDoainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}

function hostedTransaction() {
    var url = "https://xmltestapi.propay.com/ProtectPay";
    var ItemJSON;
    ItemJSON =
        '[ { "MerchantProfileId": $("txtPayerId"), "PayerAccountId":"", "Amount": $("txtAmount"), "CurrencyCode": "USD", "AuthOnly": "true", "ProcessCard": "true", "AvsRequirementType":1, "CardHolderNameRequirementType":1, "FraudDetectorsProviderName":"ThreatMetrix", "SecurityCodeRequirementType":1, "ReturnURL":  "https://example.com/ProPay_return_url.aspx" ]';

    var xhttp = createCORSRequest("PUT", url, true);
    xhttp.setRequestHeader("X-Custom-Header", "value");
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.setRequestHeader("Authorization", "Basic" + "mycreds" + ":" + "mypass");
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 & xhttp.status === 200) {
            var json = JSON.parse(xhttp.responseText);
            console.log(xhttp.responseText);
        }
    };
    var data = JSON.stringify(ItemJSON);
    xhttp.send(data);
    alert(xhttp.responseText);
    document.getElementById("lblProPayResponse").Text = xhttp.statusText + ":" + xhttp.status + "<BR><textarea rows='100' cols='100'>" + xhttp.responseText + "</textarea>"
}

function callbackFunction(xhttp) {
    console.debug(xhttp.statusText);
    alert(xhttp.responseText);
}

服务器端按钮标记如下:

<asp:Button ID="btnProPayConfirmOrder" runat="server" meta:resourcekey="btnConfirmOrder" Width="200px" Text="Confirm Order" 
onClientClick="return hostedTransaction();" UseSubmitBehavior="false"/>

当我单击测试服务器上的按钮时,出现以下错误:

Access to XMLHttpRequest at 'https://xmltestapi.propay.com/ProtectPay' from 
origin 'http://localhost' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No 'Access-Control-
Allow-Origin' header is present on the requested resource.

有可能吗?如何包含请求所需的Access-Control-Allow-Origin标头?还是有一种更好的做法?

0 个答案:

没有答案