如何从服务器向客户端发送正文消息

时间:2017-06-01 14:46:46

标签: javascript java angularjs json jersey

我有这个java服务器代码:

private Response createError(int code, String error) {
    logger.error(error);
    return Response.status(code).entity("{ \"errorMsg\": \""+error+"\"}").build();
}

和此客户端代码:

            function successCallback(response) {
                self.lastResults = response.data;
                self.filesToUpload.length = 0;
                deferred.resolve(response.data);
            }, function errorCallback(response) {
                console.log(response.data.errorMsg);
                self.filesToUpload.length = 0;
                deferred.reject(JSON.stringify(response.data.errorMsg));

            });

如何在客户端访问我在服务器响应中输入的字符串?

我尝试失败了:

response.getEntity()
VM828:1 Uncaught TypeError: response.getEntity is not a function
    at eval (eval at errorCallback (upload-service.js:114), <anonymous>:1:10)
    at errorCallback (upload-service.js:114)
    at processQueue (angular.js:16648)
    at angular.js:16692
    at Scope.$eval (angular.js:17972)
    at Scope.$digest (angular.js:17786)
    at Scope.$apply (angular.js:18080)
    at done (angular.js:12210)
    at completeRequest (angular.js:12436)
    at XMLHttpRequest.requestLoaded (angular.js:12364)
(anonymous) @ VM828:1
errorCallback @ upload-service.js:114
processQueue @ angular.js:16648
(anonymous) @ angular.js:16692
$eval @ angular.js:17972
$digest @ angular.js:17786
$apply @ angular.js:18080
done @ angular.js:12210
completeRequest @ angular.js:12436
requestLoaded @ angular.js:12364

response.entity
undefined

JSON.stringify(response)
"{"data":"<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/>\n<title>Error 500 Request failed.</title>\n</head>\n<body><h2>HTTP ERROR 500</h2>\n<p>Problem accessing /api/VoicesUploader/uploadFiles. Reason:\n<pre>    Request failed.</pre></p><hr><a href=\"http://eclipse.org/jetty\">Powered by Jetty:// 9.3.15.v20161220</a><hr/>\n\n</body>\n</html>\n","status":500,"config":{"method":"POST","transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"Accept":"application/json, text/plain, */*"},"url":"/api/VoicesUploader/uploadFiles","data":{}},"statusText":"Request failed."}"

2 个答案:

答案 0 :(得分:0)

尝试将.type(MediaType.TEXT_PLAIN)添加到您的回复中。

return Response.status(code).type(MediaType.TEXT_PLAIN).entity("{ \"errorMsg\": \""+error+"\"}").build();

答案 1 :(得分:0)

您的回复中不包含名为errorMsg的密钥。这就是所有这些: enter image description here

这个答案可能对您有用:JAX-RS — How to return JSON and HTTP status code together?