ways to deliver a message from server to client's body

Here is the Java server code I am using:

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

And this is the client code:

            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));

            });

How can I access the string from the server response in the client?

I attempted unsuccessfully to use:

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."}"

Answer №1

Consider including .type(MediaType.TEXT_PLAIN) when generating your response.

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

Answer №2

The response you provided does not contain the expected errorMsg key. Only the following information is included: https://example.com/errorimage.png

For more insights, you may find this answer helpful: How to efficiently return JSON and HTTP status code simultaneously in JAX-RS

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to decode nested JSON into a flat structure?

Is it possible in Go to unmarshal nested json into a differently structured struct, such as flattening out the nesting? { "id":1, "person":{ "name": "Jack" "extra": { "age": 21 } } } type Item struct { ID int64 `json:"id"` ...

Error occurs when Jackson attempts to serialize an object with Hibernate 5 module configured before it has been

Currently facing an issue with the Jackson FasterXML serialization to JSON when dealing with Lazily Initialized member collections of child elements in a grandchild level. Let's take a look at the entities involved: @Entity public class Parent { ...

Implementing event listeners with Angular UI-Router

Currently, I am working with Angular 1.4.5 and Angular Ui Router. I am facing an issue where I am trying to utilize addEventListener to execute a function when a text field is blurred. The challenge I am encountering is that during the load state, the elem ...

JavaScript property counterparts

Recently, I've been working on creating alias's for a specific property in my code. var default_commands = {} default_commands['foo'] = "bar"; My goal is to create multiple aliases for the key 'foo' in the object. For examp ...

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Switching a material-ui input control instead of a textfield for materials-ui-datepicker: the ultimate guide

Within my React application (v16.3), I am utilizing the DatePicker component from the material-ui-pickers library to render date-picker controls. This particular component renders a Material-UI TextField. However, I am interested in modifying it to only di ...

Switch between various API content upon clicking (JavaScript)

Upon receiving data from an API in JSON format using PHP, I aim to incorporate a filter mechanism for displaying distinct content sourced from the API. For instance, by specifying a filter in my API call, I can retrieve separate datasets such as one with ...

I encountered a "Bad Request" error when trying to login through my nodejs server, and I'm unsure of the reason behind this issue. As a beginner in nodejs, I'm still learning the ins and

passport.use(new LocalStrategy(async(email,password,done) => {    try{     const user = await User.findOne({email:email})     if(!user){        return done(null,false,{message:"Invalid email"})     }     const isValidPassword =aw ...

Numerous toggles available for the mobile version

Hey there, I need some help! I have a footer navigation on my desktop website with 3 Ul elements. I want to turn each Ul into a toggle for the mobile version. Can anyone assist me with this? Thanks in advance! <footer class="footer"> <d ...

Challenges with finding a particular button in a popup window - Selenium

I'm struggling to click on a button within a modal dialog. I've searched online for solutions, but either I'm confusing myself (a high possibility) or the suggested fixes aren't working in my specific scenario. Here's the situatio ...

What could be causing the poor performance of WebGPU in my benchmark when compared to WebGL?

After running my benchmark code on the Latest Chrome Canary on Win11 and disabling vsync with unlocked fps, I noticed that WebGPU has around 1/3 the FPS of WebGL. I'm struggling to understand the reason behind this performance difference. Here is the ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Issue with submitting VueJS form on mobile devices, works fine on web browsers but not on

I have encountered a similar problem before, but I haven't found a suitable solution yet. In my VueJS application, the submit function works perfectly fine on desktop browsers like Chrome and Firefox, but for some reason it refuses to submit on mobil ...

What is causing this JavaScript function to output '2'?

Recently, I came across an unusual JavaScript function: (function f(){ function f(){ return 1; } return f(); function f(){ return 2; } })(); To my surprise, it returns 2 instead of crashing the browsers as expected due to recursion. Curious ...

Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once. While I am aware of options like forEach or for..of for looping, I'm s ...

What is the best way to track upload progress while using Django?

Is it possible to implement an upload progress bar for a website using Django? I'm interested in tracking the progress of file or image uploads but unsure how to accomplish this. Any tips on retrieving the upload status? ...

Can anyone explain to me why the data I'm passing as props to the React functional component is displaying as undefined?

I have encountered an issue with a pre-made React component where I am unable to see the data being passed as props when I console log it. I am unsure if I am passing the prop correctly, as I have used the same prop successfully in other class-based comp ...

What is the method for obtaining the input value of an input type number in HTML?

Within my form, there is a number field where users can input scores: <input type="number" min="0" max="100" class="form-control" name="total_score" id='total_score' value="<?php echo $total_score;?>" >(Please input a score from 0-10 ...

The Vue component's data function is currently devoid of content

I've defined a Vue.js component as shown below: module.exports = Vue.component('folder-preview', { props: ['name', 'path', 'children', 'open'], template: `... `, methods: mapActions([ ...

Changing Dictionary into a formatted JSON output

The following is a dictionary: {'A': ['ABC', 'DEF'], 'B': ['GHI','JKL', 'MNO'] } I am looking to convert it into the JSON format shown below: { "type": "A", "keys": [ ...