发送像Postman一样的jquery请求

时间:2017-02-20 20:04:35

标签: javascript java jquery http 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检查权限。所以我从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文件bodycontentType的请求为空且headerparttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

然而,当从Postman发出请求方法时 - 一切正常(所以contentTypetext/plain;charset=UTF-8body{"username":"admin","password":"admin"}),这是我的Postman配置:< / p>

enter image description here

我可能误解了某些内容,但不知道为什么我的jquery请求不一样。对此有什么解决方案吗?

1 个答案:

答案 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 );
    });
});