Ajax呼叫Jquery [重复]

This question already has an answer here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/29782222/jquery-ajax-call-results-in-401-unauthorized-response-when-in-chrome-or-firefo" dir="ltr">jquery $.ajax call results in 401 unauthorized response when in Chrome or Firefox, but works in IE</a>
                            <span class="question-originals-answer-count">
                                (1 answer)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2017-09-07 15:37:25Z" class="relativetime">2 years ago</span>.</div>
        </div>
    </aside>

I am trying to make an Ajax call as follows:

$.ajax({ 
        type: "GET",
        dataType: "json",
        contentType: "application/json",
        username: "user",
        password: "admin",
        url: "http://localhost:8080/projects/1",
        xhrFields: {
            withCredentials: true
       },
        success: function(data){     
            console.log(data);
        }
    });

But I get the following error:

Failed to load resource: the server responded with a status of 401 ()

Am I missing something? (Authentication on the endpoint is HTTPBasicAuthorization)

</div>

Seems that you need to do it like this:

Full code:

headers: {
    "Authorization": "Basic " + btoa(username + ":" + password)
  },

Full code:

$.ajax({ 
        type: "GET",
        dataType: "json",
        contentType: "application/json",
        url: "http://localhost:8080/projects/1",
        headers: {
            "Authorization": "Basic " + btoa(username+ ":" + password)
        },
        success: function(data){     
            console.log(data);
        }
    });

If that doesn't work, then this should work:

 beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},