如何修复“缺少所需的请求标头。必须指定以下项之一:origin,x-requested-with'Ajax Error

时间:2019-12-10 17:14:01

标签: jquery ajax

我正在尝试使用本地前缀为实际URL /端点的CORS在本地计算机上向外部URL运行ajax调用。但是,这会导致“缺少所需的请求标头。必须指定以下一项:origin,x-requested-with'错误。我已经手动设置了标头,如下面的代码所示,我只是不太明白为什么在显式定义“ requested-with”值后仍会发生这种情况。

        // Set URL to the Create patient endpoint
        const Url = 'https://cors-anywhere.herokuapp.com/https://staging.micromerchantsystems.com/mmsgatewayapistaging/api/patient/create';

        // Define User data here ** Currently static information **
        // Need to set variables based on input value to the correct identifier
        // EX: "FirstName": $('#first_name').val();
        const userData = {
            "RequestingClient": {
                "ClientId": "XXXXXXXXXX",
                "ClientSecret": "XXXXXXXXXX",
                "MemberId": "XXXXXXXXXX"
            },
            "Pharmacy": {
                "IdentifierType": 2,
                "Identifier": "5164086800"
            },
            "LastName": "Test",
            "MiddleInitials": "X",
            "FirstName": "Seth",
            "Gender": "M",
            "DOB": "01/01/1990",
            "Email": "seth@test.com",
            "PhoneNumber": "1234567890",
            "MobileNumber": "1234567890",
            "BusinessNumber": "1234567890",
            "PatientIdentifiers": [
                { "IdentifierType": 1, "IdentifierType": "12345" }
            ],
            "AddressInformation": {
                "AddressType": 1,
                "StreetLine1": "123 Test",
                "StreetLine2": "",
                "City": "Waco",
                "State": "TX",
                "ZipCode": "76710",
            },
            "ExternalPatientId": "1234567890",
            "Timestamp": "2019-12-09T17:59:15.7624947Z"
        };

        // On button ajax call to create a new user with the above data
        $('.btn').click(function () {
            $.ajax({
                url: Url,
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                // set the request header authorization to the bearer token that is generated
                headers: {
                    "X-Requested-With": "XMLHttpRequest",
                    "Authorization": "Bearer " + responseToken,
                },
                data: userData,
                success: function (result) {
                    console.table(result);
                    $('.output_userInfo').html(result.ErrorMessage);
                },
                error: function (error) {
                    console.log(`Error ${error}`)
                },
            });


        });

2 个答案:

答案 0 :(得分:0)

您正确设置了标题,但是根据cors-anywhere的作者,由于以下原因,您可能会遇到与发出请求相关的错误(即使在设置了适当的标题之后):

  • 您要代理的URL不可访问(例如,站点已关闭,或者它们已阻止访问CORS Anywhere IP)。
  • 在给定的时间范围内,给定的来源已将太多请求发送到CORS Anywhere #45)。
  • URL本身已被列入黑名单(例如#32#42)。
  • CORS Anywhere处于关闭状态。(即,如果您是自托管的,则适用)

基于对目标URL(https://staging.micromerchantsystems.com/的请求),我得到了一个IIS初始屏幕,因此您可能要验证所有内容是否都在运行。使用下面的一个非常简单的示例,我似乎能够访问正确的站点,但是收到401错误,表明我未经授权(但是我没有收到400要求的标头消息):

$(function() {
  $.ajax({
    url: "https://cors-anywhere.herokuapp.com/https://staging.micromerchantsystems.com/mmsgatewayapistaging/api/patient/create",
    type: "POST",
    dataType: "json",
    contentType: "application/json",
    // set the request header authorization to the bearer token that is generated
    headers: {
      "X-Requested-With": "XMLHttpRequest"
    },
    success: function(result) {
      console.log(result);

    },
    error: function(error) {
      console.log(`Error ${error}`)
    },
  });
});

我想如果您包括适当的授权信息,您应该能够访问它。如果您仍然遇到问题,则可能需要consider reaching out to the author谁可能会帮助您进一步解决问题。

答案 1 :(得分:0)

我做了一些进一步的研究,以便能够成功运行Postman代码并从中获得正确的答案。这是我用来正确运行API并跨域传递信息的代码。

        // Set URL to the Create patient endpoint        
        const Url = "https://cors-anywhere.herokuapp.com/https://staging.micromerchantsystems.com/mmsgatewayapistaging/api/patient/create";

        // On button ajax call to create a new user with the above data

        $('.btn').click(function () {
            // The input value variables NEED to be defined and set after the click function
            // so that the value can be received and passed into the userData variable.

            // Define User data here ** Currently static information **
            // Need to set variables based on input value to the correct identifier
            // EX: "FirstName": $('#first_name').val();
            var user_firstName = $("#first_name").val();

            const userData = {
                "RequestingClient": {
                    "ClientId": "XXXXXX",
                    "MemberId": "XXXXXXX"
                },
                "Pharmacy": {
                    "IdentifierType": 2,
                    "Identifier": "XXXXXXX"
                },
                "LastName": "Test",
                "MiddleInitials": "X",
                "FirstName": user_firstName,
                "Gender": "M",
                "DOB": "01/01/1990",
                "Email": "seth@test.com",
                "PhoneNumber": "1234567890",
                "MobileNumber": "1234567890",
                "BusinessNumber": "1234567890",
                "PatientIdentifiers": [
                    { "IdentifierType": 1, "IdentifierType": "12345" }
                ],
                "AddressInformation": {
                    "AddressType": 1,
                    "StreetLine1": "123 Test",
                    "StreetLine2": "",
                    "City": "Waco",
                    "State": "TX",
                    "ZipCode": "76710",
                },
                "ExternalPatientId": "1234567890",
                "Timestamp": "2019-12-09T17:59:15.7624947Z"
            };

            // Using stringify is an important part in successfully passing the data
            var userString = JSON.stringify(userData);



            var userSettings = {
                "async": true,
                "crossDomain": true,
                "url": Url,
                "method": "POST",
                "headers": {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + responseToken,
                    "Accept": "*/*",
                },
                "data": userString
            }

            $.ajax(userSettings).done(function (response) {
                console.table(response);
            });
        });