【发布时间】:2017-07-10 05:59:25
【问题描述】:
我尝试从我的 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"}),这是我的 Postman 配置:
我可能误解了一些东西,但不知道为什么我的 jquery 请求不一样。有什么解决办法吗?
【问题讨论】:
-
您可以尝试使用 ajax 请求的数据类型作为 dataType : "text" 而不是 dataType : "json"。您期望从服务器返回的数据类型。
-
我试过了,但没有帮助
标签: javascript java jquery http postman