1. ホーム
  2. jquery

[解決済み】「Missing required request header」を修正する方法。origin,x-requested-withのいずれかを指定する必要があります' Ajax Error

2022-01-18 05:12:17

質問

実際のURL/エンドポイントの前にCORS anywhere urlを使用して、ローカルマシンから外部URLへのAjaxコールを実行しようとしています。しかし、その結果、「Missing required request header. Must specify one of: 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": "[email protected]",
            "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}`)
                },
            });


        });

解決方法は?

正常に実行できた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": "[email protected]",
                "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);
            });
        });