[英]How do I add basic auth headers to a post request that returns html?
對於我正在處理的項目之一,有一個POST端點受基本身份驗證保護,返回HTML表單。 這是使用快速服務器托管並使用護照的基本身份驗證進行保護。 我想要另一個HTML表單,其中包含一個按鈕,單擊該按鈕時會在瀏覽器中加載該html。 我試着有一個類似於這個的表格:
<form method="post" action="http://username:password@localhost:8080/endpoint">
<input type="submit">
</form>
但是當單擊按鈕並檢查服務器上的auth標頭時,它們似乎未設置(req.headers.authorization = undefined)。 我知道我可以使用Javascript設置auth標頭,但如果我這樣做,我不知道如何在該頁面的瀏覽器中加載html。 那么,如何處理需要基本auth頭的端點,使用post訪問並返回HTML? 這看起來應該很容易,但我不知道該怎么做。
您需要在javascript中添加auth標頭。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
<input type="submit">
</form>
<script type="application/javascript">
$("#myForm").submit(function (e) {
var url = 'http://localhost:8080/endpoint';
var username = 'username';
var password = 'password';
$.ajax
({
type: "POST",
url: url,
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
data: '{ "comment" }',
success: function (response){
$(body).empty();
$(body).html(response);
}
});
e.preventDefault();
});
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.