Tips for utilizing JSON.parse

Within my ajax request, I am encountering the following code:

    403: function(jqXHR) {
                var error = jqXHR.responseText;
                console.log(error);
            }

When this error occurs, a message is displayed in the console:

HttpError: Wrong password<br> &nbsp; &nbsp;at 
c:\Users\...path...js:18:29<br> &nbsp; &nbsp;at 
c:\Users\...path...\async.js:52:16<br> &nbsp; &nbsp;at 
Immediate._onImmediate 
(c:\Users\...path...\node_modules\async\lib\async.js:1201:34)<br>
&nbsp; &nbsp;at processImmediate [as _immediateCallback] 
(timers.js:383:17)

Attempting to parse this error and retrieve the error.message results in the following console output:

var error = JSON.parse(jqXHR.responseText);
    console.log(error.message);

A message then appears in the console indicating:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
.complete()
m.Callbacks/j()
m.Callbacks/k.fireWith()
x()
.send/b()

The server-side code related to this issue is as follows:

schema.statics.authorize = function(username, password, callback) {
        var User = this;

        async.waterfall([
            function(callback) {
                User.findOne({username: username}, callback);
            },
            function(user, callback) {
                if (user) {
                    if (user.checkPassword(password)) {
                        callback(null, user);
                    } else {
                        callback(new AuthError("Wrong password"));
                    }
                } else {
                    var user = new User({username: username, password: password});
                    user.save(function(err) {
                        if (err) return callback(err);
                        callback(null, user);
                    });
                }
            }
        ], callback);
    };


    exports.User = mongoose.model('User', schema);




    function AuthError(message) {
        Error.captureStackTrace(this, AuthError);

        this.message = message;
    }

    util.inherits(AuthError, Error);

    AuthError.prototype.name = 'AuthError';

    exports.AuthError = AuthError;

I am seeking guidance on how to properly display an error message using console.log.

Answer №1

Here is an alternate solution: let errorMsg = JSON.parse(jqXHR.responseJSON); console.log(errorMsg.message);

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

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

Is there a way to attach a model to an Angular directive?

Currently, I am implementing angular's typeahead functionality using the following resource: I have created a directive with the following template: <div> <input type="text" ng-model="user.selected" placeholder="Ty ...

Error encountered during npm install and node-gyp build on one out of two identical machines

I am facing an issue while trying to run npm install on my Ubuntu 14.04 VPS specifically when it comes to installing karma. Even though the command npm install is being executed from a Jenkins build step, it still fails both from the command line as well a ...

Persistent Angular Factory Variables Showing Outdated Data - Instances Stuck with Old Values

One of the challenges I faced was setting up a resource factory to build objects for accessing our API. The base part of the URL needed to be determined using an environment variable, which would include 'account/id' path segments when the admin ...

Adjusting runtime environment variables for a React application

I have a React Application that needs to be deployed to Cloud Foundry and I am looking for a way to segregate the development, staging, and production environments. The challenge is that React only provides .env.development for running the application usin ...

Regularly check in with the server via ajax calls

I have a page that needs to send periodic "background" ajax requests after it is loaded. These requests should be sent at specific time intervals. Would using cron be the best option for this task, considering that I have never used it before? Are there a ...

The contrastText property of the MUI React Theme palette is not functioning properly

I am working with MUI React to design a menu and I have utilized the AppBar component. I would like to customize it in the following way: brown.myBrown = '#544846'; const brownTheme = createTheme({ palette: { primary: { ma ...

The issue with React Testing using Jest: The domain option is necessary

I've recently developed a React app that implements Auth0 for Authentication. Right now, I'm working on setting up a test suite using Jest to test a specific function within a component. The function I want to test is createProject() in a React ...

Enhancing nouislider jQuery slider with tick marks

I have integrated the noUIslider plugin () into one of my projects. I am seeking guidance on how to display tick marks below each value on the slider. This is the current initialization code for the slider: $slider.noUiSlider({ 'start': sta ...

What is causing the "unable to resolve dependency tree" error when using ng new newApp?

Struggling with creating a new Angular app using the command ng new app-name? When running the command, you may encounter the following error in the command line. Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve depen ...

Passport offering Residences/Assistants for Locals

After successfully replacing the everyauth/ mongoose-auth login system with a passport implementation, I am now utilizing the passport-local module for local username/password logins. While exploring some examples, I noticed that Passport automatically as ...

What is the best way to adjust the placement of a component to remain in sync with the v-model it is connected to?

I am encountering an issue with 2 sliders in my project. I have set it up so that when the lower slider's value is greater than 0, the top slider should automatically be set to 5. I am using a watcher function for this purpose. However, if I manually ...

What is causing the incorrect characters in my Azure appsettings encoding?

I'm encountering an issue with the encoding of Azure appsettings. My node.js application is deployed on an app service. When attempting to access environment variables using process.env, the values are coming in with incorrect encoding. I was expecti ...

Incorporate 'Additional features' into the Navbar when adjusting window size

When the window is resized, I want to display a collapsed 'More options' button that will collapse all hidden <li> elements. Here is an example: <li id="menu_more_container" class="dropdown" style="display: none; ...

Express JS redirect does not update the URL and fails to load static files

I'm currently developing an application using Express.js to build the REST interface on Node.js. Additionally, I am using jQuery Mobile for the client-side pages. One issue I am facing is with redirects when users try to access a restricted or inacce ...

Top method for managing missing sub-documents in MongoDB query outcomes

I've seen this question asked in various forms before, but I'm seeking the most efficient way to manage query results without relying on multiple if statements. Imagine I need to locate a product (sub-document) within a package (document) Packa ...

Unusual problem encountered on Safari when utilizing jQuery's ajax() function

The issue I am facing is specific to the current version of Safari on Mac. (Older versions of Safari might be affected, but they are not relevant in this case) Only Safari is returning a generic 500 error every time. There seems to be a problem with the ...

Issue: Encounter of "Uncaught (in promise) TypeError" while implementing RiveScript chatbot in Angular

I've been working on integrating a chatbot based on RiveScript into Angular. The chatbot is functioning well - I always see the correct response in the console. Displaying the user's input is also working seamlessly. However, I'm encounterin ...

Encountering an error stating, 'Cannot read property 'match' of undefined' while running npm install, however finding a solution only provides temporary fix

To solve this recurring issue, I have been consistently deleting node_modules and package_lock.json. While this temporary fix works initially, the problem persists after each npm install. Here's my debug log: 0 info it worked if it ends with ok 1 ver ...

What could be causing my TypeScript code to not be recognized as CommonJS?

I rely on a dependency that is transpiled to ES6. My goal is to leverage ES2019 features in my own code. Ultimately, I aim to output ES6. This is how I set up my tsconfig { "compilerOptions": { "module": "CommonJS" ...