ngResource transformResponse guide on dealing with both successful and erroneous responses

When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401).

This poses a challenge on my frontend, where I utilize Angular's ngResource. The resource code looks like this:

svc.authenticateApi = function() {
            return $resource(apiEndpoint + 'authenticate', null, {
                'save': {
                    method: 'POST',
                    transformResponse: function (data, header) {
                        console.log("transformResponse, header:", header());
                        console.log("transformResponse, data:", data);

                        return { data: angular.fromJson(data) };
                    },
                },
            });
        };

Everything works seamlessly when the API returns normal JSON data. However, when an error status is returned, the data parameter is not in serialized JSON format; instead, it appears as plain text. This leads to errors such as:

https://i.stack.imgur.com/rLeCP.png

It seems that the transformResponse function attempts to interpret the text "Unauthorized" as JSON and fails. I could address this problem by ensuring that every error response from the server is sent as JSON, for example by calling `res.status(401).send({error: "Unauthorized"}); however, this workaround feels like a hack, and I would prefer not to manually repeat error messages for each status code.

Is there a more efficient way to handle this issue? I don't mean to sound like I am complaining, but the ngResource documentation is lacking, and I am starting to consider using $http as a better alternative solution.

Answer №1

After transitioning away from $resource, my preference now lies with using $http throughout my projects. There's just something about $resource that doesn't quite sit well with me. However, I do believe that receiving JSON data from the server in all cases is the most effective approach. While it is possible to create a custom handler to test incoming responses and work around issues, this solution doesn't feel completely satisfactory to me.

I suspect that the error may be originating from the line where { data: angular.fromJson(data) } is returned. It might be worth considering wrapping this block of code in a try/catch statement for added robustness.

Answer №2

After taking Mike Feltman's advice to heart, I found a successful solution by encapsulating the fromJson function in a try / catch block. This approach ensures that if an error occurs, there is no need to proceed with transforming the response.

function handleErrors(originalData) {
    var transformedData;

    try {
        transformedData = angular.fromJson(originalData);
        /* code for data transformation */
    } catch (error) {
        /* return original data as there is no transformation needed */
        transformedData = originalData;
    }
    return transformedData;
}

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

JQuery Submission with Multiple Forms

Hey everyone! I have a jQuery form with multiple fieldsets that switch between each other using jQuery. Eventually, it leads to a submit button. Can someone assist me by editing my jfiddle or providing code on how I can submit this data using JavaScript, j ...

Combine, condense, and distribute JavaScript files using Express without applying gzip compression to the response

Currently, I am developing a web application using Express. My goal is to merge, minify, and serve .js files efficiently. To achieve this, I have created a middleware with the following code: var fs = require('fs'), path = require('path ...

Separating stylesheets, head, and other elements in a curl response

After successfully using curl to retrieve an external site, I noticed that the results were interfering with my own content. The CSS from the external site was affecting my webpage's layout and z-index values were conflicting. I am seeking a solution ...

Removing a row from MySQL using JQuery Ajax

Hello there! I'm currently facing an issue while trying to remove a row from a MySQL database using PHP and AJAX. I initially thought it would be a simple task with $.ajax {}, but unfortunately, the row is not getting deleted for some reason. Here&apo ...

Encapsulate the HTTP request within a common function for reus

My rest-provider service handles all of my http calls, but I've noticed that each function is repeating a lot of the same http code. It seems like I should create a shared function to avoid this repetition and make it easier to update in the future. ...

How can we efficiently execute text searches on a large scale by utilizing static index files that are easily accessible online

Looking for a lightweight, yet scalable solution for implementing a full text search index in JavaScript using static files accessible via HTTP? Seeking to make about 100k documents searchable online without breaking the bank on hosting costs like Elastics ...

What is the best way to fill a list-group using JavaScript?

Fetching ticket data from a controller is done using the code snippet below: $.ajax({ type: "GET", url: "/Tickets/List/", data: param = "", contentType: "application/ ...

Using Redux with Next.js to implement getStaticPaths

Can someone help me understand how to implement getStaticPaths in conjunction with Redux in Next.js? I'm currently using next-redux-wrapper to manage my content, but I am encountering issues when trying to display the data. Below is a snippet of my ...

Conceal the Angular alert message automatically after a specified number of seconds or when the page

I recently started working with Angular and managed to implement an alert message for password reset requests in our app: Usermodel: .service('userModel', ['$q', '$http', 'authorizedTracker', function($q, $http, au ...

Locating the source and reason behind the [object ErrorEvent] being triggered

I'm facing an issue where one of my tests is failing and the log is not providing any useful information, apart from indicating which test failed... LoginComponent should display username & password error message and not call login when passed no ...

Understanding Mongodb: the process of populating a schema that is referenced within another schema using an API

Looking to make adjustments to my Api in order to populate a referenced schema. Here's the schema I am working with: export const taskSchema = new Schema ({ user:{ type: String, required: true }, project: { type ...

Creating a Dynamic Slideshow on Autopilot

My JavaScript skills are not perfect and I'm feeling a bit lost. I have this code for a slideshow, but I want to make it automatic while also allowing users to navigate between images freely. I'm struggling to figure out how to implement this fun ...

When attempting to change the text in the textarea by selecting a different option from the dropdown list, the text is not updating

I am facing an issue with three multi-select dropdown lists. When a user selects options from these lists and then presses the submit button, the selected text should display in a textarea. However, if the user manually changes some text in the textarea ...

Struggling with the addition of the 'Other' option in React manually. Any tips or suggestions?

I've encountered a slight issue regarding the functionality of my React Component below. Specifically, I want users to have the ability to enter a poll category that is not listed in the select component options by using an input field. This scenario ...

The Daterangepicker function moment() outputs numerical values

Within my .cshtml file, I have integrated a daterangepicker.js script. This page retrieves the date range (from date, to date) from a parent page using ViewBag. The code snippet is as follows: var _FromDate; var _EndDate; $(function () { var from1 = ...

Guide on embedding PHP/MYSQL array into an independent JavaScript document

I'm looking for guidance on how to insert an array from a PHP MySQL page into a separate JavaScript file. Can someone please help me with indicating where to include the PHP URL and provide the correct format for the PHP array code in order to achieve ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...

A step-by-step guide on how to repeatedly reload a nextJS page using recursion and display an error page once the

I've been experimenting with a recursive page reload function that looks like this: export const refreshPage = (count)=>{ if (count <= 0){ // window.location.reload(); console.log("blue"); return }else { console.log(& ...

Tips for handling daily JavaScript tasks using Angular JS

Over the past few days, I've been diving into AngularJS. While it seemed intuitive in tutorials and videos, when I actually started replacing my current web app code with AngularJS, I encountered numerous issues. For instance, if I wanted to add HTML ...

Maximizing the potential of .delegate in combination with .closest

$('.inputRadio').parent().click(function (e) { //implement delegate method here }); Looking for assistance on how to integrate the delegate method in the provided function. Any suggestions? ...