【问题标题】:Send jquery request like Postman像 Postman 一样发送 jquery 请求
【发布时间】: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 发送请求,文件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 配置:

我可能误解了一些东西,但不知道为什么我的 jquery 请求不一样。有什么解决办法吗?

【问题讨论】:

  • 您可以尝试使用 ajax 请求的数据类型作为 dataType : "text" 而不是 dataType : "json"。您期望从服务器返回的数据类型。
  • 我试过了,但没有帮助

标签: javascript java jquery http postman


【解决方案1】:

成功的 Postman 请求表明您的后端设置正确。您的请求方法可能有问题。删除您在第 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 );
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2017-01-22
    • 2020-09-28
    相关资源
    最近更新 更多