[英]Send jquery request like Postman
我試圖從我的javascript文件發送一些post
方法,但出了點問題,腳本不起作用。 我的html
文件是:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script> <script>
$( document ).ready(function() {
var request = $.ajax({
method: "POST",
url: "http://localhost:8081/login",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { username: "John", password: "Boston" }
})
.done(function( msg ) {
alert( "Done: " + msg );
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
</script>
</head>
<body>
</body>
</html>
我使用spring-boot
作為服務器,並希望通過使用JWT檢查權限。 所以我從AbstractAuthenticationProcessingFilter
類中覆蓋了attemptAuthentication
方法:
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws AuthenticationException, IOException, ServletException {
String contentType = httpServletRequest.getContentType();
String headerPart = httpServletRequest.getHeader("Accept");
String body = httpServletRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
AccountCredentials credentials = new ObjectMapper().readValue(httpServletRequest.getInputStream(),AccountCredentials.class);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
return getAuthenticationManager().authenticate(token);
}
如果我從html
文件body
發送請求並且contentType
為空且headerpart
為text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
但是當從Postman發出請求方法時 - 一切都運行正常(所以contentType
是text/plain;charset=UTF-8
, body
是{"username":"admin","password":"admin"}
),這里是我的郵差配置:
我可能誤解了一些東西,但不知道為什么我的jquery請求不一樣。 這有什么解決方案嗎?
成功的郵遞員請求表明您的后端已正確設置。 您的請求方法可能有問題。 刪除在第5行上使用的變量綁定。
這里的JQuery AJAX語法是一個類似問題的鏈接。 https://www.w3schools.com/jquery/ajax_ajax.asp指向w3學校用例的鏈接。
您的代碼應如下所示:
$( document ).ready(function() {
$.ajax({
method: "POST",
url: "http://localhost:8081/login",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { username: "John", password: "Boston" }
})
.done(function( msg ) {
alert( "Done: " + msg );
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.