我尝试从我的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检查权限。所以我从attemptAuthentication
class:
AbstractAuthenticationProcessingFilter
方法
@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"}
),这是我的Postman配置:< / p>
我可能误解了某些内容,但不知道为什么我的jquery请求不一样。对此有什么解决方案吗?
答案 0 :(得分:0)
成功的邮递员请求表明您的后端已正确设置。您的请求方法可能有问题。删除在第5行使用的变量绑定。
JQuery AJAX syntax这是指向类似问题的链接。 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 );
});
});