簡體   English   中英

發送像Postman一樣的jquery請求

[英]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為空且headerparttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

但是當從Postman發出請求方法時 - 一切都運行正常(所以contentTypetext/plain;charset=UTF-8body{"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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM