簡體   English   中英

為什么 HttpServletResponse 正文總是空的?

[英]Why is HttpServletResponse body always empty?

我的客戶端正在使用 fetch api 與 Controller 方法進行交互,該方法將解密密碼並將解密后的密碼以純文本形式發送回客戶端。 但是,響應正文從不包含密碼。 即使我將其設置為text/plain ,它也會繼續將內容類型設置為basic類型。 我究竟做錯了什么?

客戶

            function showCredentialModal(credentialId, url, username, password) {
                $('#credential-id').val(credentialId ? credentialId : '');
                $('#credential-url').val(url ? url : '');
                $('#credential-username').val(username ? username : '');

                // Display encrypted password if the current user is not the owner of the credential
                if (password) {
                    fetch('/credentials/decrypt?credentialId=' + credentialId)
                        .then(response =>
                            console.log(response))
                        .catch(() =>
                            $('#credential-password').val('error'));
                } else {
                    $('#credential-password').val('');
                }

                $('#credentialModal').modal('show');
            }

Controller

    @GetMapping("/decrypt")
    public void doGet(HttpServletResponse response,Authentication authentication,
                                     @ModelAttribute Credential credential) throws IOException {
        User user = getCurrentUser(authentication);
        credential = credentialService.getCredential(credential.getCredentialId());

        boolean result = validationService.validate(credential, user);
        if (result) {
            String decryptedPassword = credentialService.decryptPassword(credential);

            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");
            try (PrintWriter out = response.getWriter()) {
                out.print(decryptedPassword);
                out.flush();
            }
        }
    }

回復:

Response {type: "basic", url: "http://localhost:8080/credentials/decrypt?credentialId=1", redirected: false, status: 200, ok: true, …}
body: ReadableStream
locked: false
__proto__: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: "http://localhost:8080/credentials/decrypt?credentialId=1"
__proto__: Response

嘗試調試。 實際上寫的東西很難理解。 這可能是某些情況,但請確保“結果”始終返回錯誤。 一些調試問題:

  1. 方法 getCurrentUser() 可以與 null 一起使用嗎?
  2. 憑據ID; 它從您在 fetch 方法中傳遞的 URL 參數中消耗。

我建議使用 Spring 文檔中的示例重寫此代碼。 現在看起來您從不同的指南中復制了一些片段。

您的客戶端只是將響應打印到控制台:

.then(response => console.log(response))

它顯示了帶有未使用的ReadableStream主體的響應:

body: ReadableStream
...
bodyUsed: false

您需要閱讀該 stream 的內容以獲取 servlet 返回的內容。 參見例如:

現在您只是將響應轉儲到控制台,它的字符串表示不是您期望的(即它不是內容,而是它的包裝器)。 您的 servlet 代碼似乎很好,這是您的 JavaScript 客戶端需要修改以從響應中讀取內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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