Error encountered: Parsing error with Angular $HTTP response due to an unexpected token "E

Here is an example of how to make a simple POST call using the Angular $HTTP service: authService.login = function(username, password){ var credentials = 'username=' + username + '&' + 'password=' + password;

        return $http({
            method: 'POST',
            url: href,
            headers: {'accept': acceptValue, 'content-type': contentType},
            data: credentials
        }).then(onSuccess, onError);
    };

I am encountering an issue where I can't retrieve the error status. Instead, I am getting a SyntaxError: Unexpected token E. The console initially shows the status 401 and then immediately displays the parse error. I'm curious about what is causing this issue behind the scenes, what it is attempting to parse, and why I am unable to access error.status.

Answer №1

The issue may lie in the way you are handling your data serialization. Instead of manually constructing the string, consider passing the data directly into the data property as an object:

data: {username: username, password: password}

Angular is capable of automatically serializing the information within the data object.

If this approach does not work, Angular offers an alternative serializer that emulates the one found in jQuery. You can find documentation on this feature here. To make a request using this method, it would look something like the following:

            $http({
                url: "/auth/login",
                method: "POST",
                headers: {"Content-Type": "application/x-www-form-urlencoded"},
                data: $httpParamSerializerJQLike({
                    email: email,
                    password: password
                })
            })

If you opt for this solution, remember to inject $httpParamSerializerJQLike as a dependency.

Answer №2

It appears that your request has been successfully sent and you have received a response.

I experimented with a RESTful service that returned a status code of 401. Below is the JavaScript code I used:

var href = 'https://contactsapi.apispark.net/v1/contacts/';
var acceptValue = 'application/json';
var contentType = 'application/json';
var credentials = {}; //'something';

function onSuccess(data, status, headers, config) {

}

function onError(data, status, headers, config) {
  console.log('data = '+JSON.stringify(response, null, 2));
}

$http({
    method: 'POST',
    url: href,
    headers: {'accept': acceptValue, 'content-type': contentType},
    data: credentials
    }).then(onSuccess, onError);

In my case, the response object contained the following information:

{
  "data": {
    "code": 401,
    "contactEmail": null,
    "description": "The request requires user authentication",
    "homeRef": "/",
    "reasonPhrase": "Unauthorized",
    "uri": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2"
  },
  "status": 401,
  "config": {
    "method": "POST",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "url": "http://localhost:8182/contacts/",
    "headers": {
      "accept": "application/json",
      "content-type": "application/json"
    },
    "data": {}
  },
  "statusText": "Unauthorized"
}

To troubleshoot, it may be helpful to examine the response content (headers / payload). Check if there is consistency between the actual content and the specified Content-Type header. For instance, receiving plain text content with a application/json content type could indicate a discrepancy.

I conducted a test to replicate such a scenario (XML content with an application/json content type) and encountered this error:

SyntaxError: Unexpected token <
  at Object.parse (native)
  at vc (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:15:480)
  at Zb (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:82:229)
  at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:83:143
  at m (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:7:322)
  at dd (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:83:125)
  at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:84:380)
  at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:119:113
  at n.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:133:221)
  at n.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:130:233)

Angular attempts to parse malformed JSON content, resulting in an error.

This issue seems similar to what you are experiencing. It suggests that the problem lies within the server rather than your Angular application.

Hoping this provides insight, Thierry

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

AngularJs allows for the insertion of section IDs in HTML

Is there a way to dynamically set the id attribute of an html section based on a condition using AngularJs? I attempted using "<section ng-attr-id="{'blue' : character.name=='John', 'pink' : character.name=='Jenny&apos ...

Using PHP and Angular.js to pass return value to error callback function

Is there a way to handle error callbacks in PHP and angular.js when an SQL query fails to execute? Let me share my code below for better understanding. session.php: <?php session_start(); $connect = mysqli_connect("localhost", "root", "Oditek123@", ...

Capturing an error within an asynchronous callback function

I am utilizing a callback function to asynchronously set some IPs in a Redis database. My goal is to catch any errors that occur and pass them to my error handling middleware in Express. To purposely create an error, I have generated one within the selec ...

Tips for effectively handling errors in NodeJS

As I venture into the world of NodeJS and Express, I find myself faced with the challenge of asynchronously calling DB functions. This is quite different from my experience with other popular scripting languages and a C++ background. Despite figuring out a ...

Display a hyperlink in an iframe on the main page from a different domain using JavaScript

I'm currently using Angular with Wirecard as my payment provider. When I need to add a payment, I open an iframe that directs the user to the Wirecard site to accept the payment. Once the user clicks accept, I provide a link back to my site from Wirec ...

preserve unique data through an asynchronous procedure without redundancy

In this MEAN Stack project, my goal is to store documents in the same collection with: various types a unique chronological number per type. For example: {ID: 1, type: 'a', chrono: 1} {ID: 2, type: 'b', chrono: 1} {ID: 3, type: &a ...

ng-if is executed prior to the specified time

This unique Soundcloud player was created using Plangular, a directive that utilizes AngularJS and the Soundcloud API. Due to certain restrictions with third party apps not being able to stream some Soundcloud tracks, I have implemented ng-if="track" and n ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

Leveraging the power of Vue.js for a solo project

I've been diving into learning Vue.js for my job, and while I've grasped the syntax, I have a specific query regarding setting up a full project. Up to this point, I've used npm to start a project, either through the command line or by util ...

Colorbox: Display a specific section from a separate HTML page

Currently, I am facing a challenge where I need to open just one specific part of an external HTML page in a colorbox. I attempted the following approach, however it is opening the entire page instead of just the specified part (at the div with id="conten ...

Place the script tags within the window.load function inside the head section

<head> <script type="text/javascript"> $(window).load(function() { // <script src="js/external.js"></script> // }); </script> </head> Is it possible to insert a script tag(< script src="js/exte ...

execute a synchronous function within a promise

Recently diving into the world of JavaScript and asynchronous operations, I found myself working on a Node.js router with Express that pulls weather data from MongoDB using Mongoose. This data is collected from various sites at 15-minute intervals and proc ...

Converting lists to JSON format in a C# web form

Utilizing JSON.stringify, I have implemented textbox autocomplete for a web-form that suggests city names based on user input. The goal is to retrieve relevant city names from the database and display them as suggestions in the autocomplete feature after t ...

The findOne() function is providing the complete model instead of a specific document as expected

When using findOne() to extract a document, the correct result is printed when the returned value is logged. However, when looping over it, the model is printed instead of the original document stored in the City table: { _id: 62e135519567726de42421c2, co ...

Establishing a read stream from a folder and transferring the entire contents of the folder to a MongoDB Bucket

I encountered an issue while attempting to save an entire directory to a MongoDB Bucket. Although the process is successful when I zip the file, I specifically need the files to be uploaded in their unzipped format into the bucket. However, when I try to ...

Enhancing Images in Next JS

Is there a way to incorporate the NextJS Image element into raw HTML response from the server, such as the following example: HTML = "<div> <p> Some Random text</p> <img src="image1.jpg" /> <img src="image2. ...

Refreshing the settimeout function through a click event

I'm working on a feature where I use setTimeout to dynamically change the font size of paragraphs. My goal is to have the font size reset when the user clicks on the "reset" button or initiates the timer again. However, I've encountered an i ...

Extracting Ajax responses and storing them as variables in JavaScript

Currently, I am developing a small PHP script and using the following code for an ajax query: var CODE = $('.code').val(); var CASE = $('.code').attr('case'); $.ajax({ type:'POST', ...

Deciphering the issue: "Error: ng:areq"

Hello, I have developed a sample program using Ionic framework. In the app.js file of my Ionic project, I defined a variable as follows: (var itemCheck=angular.module('Shop',['ionic','starter.controllers']);) Below is a snipp ...

The functionality of app.get('') is malfunctioning in Node.js when it comes to handling query parameters

I'm currently working on updating my conversation application to handle new routes that accept parameters and pass them along to the client side. However, I'm facing an issue with the .get() method not rendering the HTML as expected. 'use s ...