Ionic 3 and Angular 6: Json Input Ended Abruptly

I've come across numerous discussions about the error I'm experiencing, but none of the solutions seem to apply to my situation. This morning, when I ran my code, I encountered the "Unexpected end of Json Input" error. Interestingly, I hadn't made any changes to my code or updated any packages. Strangely, the same code works perfectly fine on my colleague's computer even though we have identical packages and versions.

The issue arises when I make a request to the server - it responds with a "status 200 ok" message, but the response body is empty as shown in the image below.

https://i.sstatic.net/0SWzr.png

Additional details about the error can be found in this image:

https://i.sstatic.net/z8zmS.png

Below is a snippet of the code causing the error:

     console.log(localStorage.getItem("usedURL"));
    return new Promise((resolve, reject) => {
        let headers = new Headers();

        headers.append('Accept', 'application/json');
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        this.http.post(localStorage.getItem("usedURL")+"/login", JSON.stringify({ "UserName": credentials.email, "Password": credentials.password }), { headers: headers})
            .subscribe(res => {
                console.log(res);
                resolve(res.json());
            }, (err) => {
                reject(err);
            });
    });

Despite my efforts to troubleshoot by clearing the cache, deleting node modules, and even copying my colleague's code, the issue persists. I'm starting to think that the problem may not be related to the code itself. Does anyone have any ideas on how I can resolve this issue?

Thanks.

Answer №1

Can you please share which version of Chrome you currently have installed? If you are using the most recent version, consider downgrading to see if that resolves the issue :). Anytime!

Answer №2

If the images are not loading,

Response:

Response {_body: "", status: 200, ok: true, statusText: "OK", headers: Headers, …}
headers: Headers {_headers: Map(0), _normalizedNames: Map(0)}
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://myapiurl//login"
_body:"" 
__proto__: Body

Details of the error:

ERROR SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.js:1091)
    at SafeSubscriber._next (account-auth-service.ts:109)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:242)
    at SafeSubscriber.next (Subscriber.js:189)
    at Subscriber._next (Subscriber.js:129)
    at Subscriber.next (Subscriber.js:93)
    at XMLHttpRequest.onLoad (http.js:1591)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4751)

Answer №3

The error you are experiencing is due to the response you are receiving.

Essentially, your response body is "", and when you attempt to JSON.parse(""), you will encounter the error you are seeing, which is:

ERROR SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)

Therefore, it appears that the error stems from the response you are receiving. The question now is why your API is returning an empty string. Unfortunately, without seeing your API login code, it is difficult to ascertain the reason. Please provide your API login code or consider posting a new question for further assistance.

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

Hiding the right CSS border for every even number in AngularJS using a loop

I am currently in the process of building an application using AngularJS and the Ionic framework. My goal is to display a right border only for odd numbers. Below is the snippet of my code: <div class="media-body" style="padding-bottom:25px;"> ...

What is the best way to include an item in a list with a specific identifier using the useState Record data type in a React application built with TypeScript?

Here is the structure of my Record type: const PEOPLE_MAP_INIT: Record<string, Person[]> = { "1": [], "2": [], "3": [] }; I have initialized the useState like this: const [PEOPLE_MAP, SET_PEO ...

Nested objects in Gson are objects that are contained within another

In my current project, I am utilizing a library that includes a class designed to map a JSON message. Gson is being used to serialize the classes into JSON format. Within the message structure, there is a data field that is generic and can contain any type ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...

Unable to retrieve specific key from NSDictionary within FourSquare API venues

I am facing an issue while trying to access the "prefix" and "suffix" strings from the provided FourSquare NSDictionary. Despite attempting different methods in my nsobject, I have not been successful so far. Is there a straightforward way to extract these ...

Implementing Facebook Javascript SDK to enable login and trigger re-authentication using React Web and Typescript within a component

As a newcomer to stack overflow, I welcome any suggestions on how I can improve my question. I'm in need of guidance concerning logging a user into facebook and requiring them to authenticate their profile or select another profile manually, rather t ...

Is there a way to manage null JSON data?

Upon receiving JSON data from the server, I proceed to send a post request for deletion. If the JSON data matches this format, there are no issues and I can easily parse it: {"tables":[{"id":"1","number":"4"},{"id":"2","number":"1"},{"id":"3","number":"2 ...

Display JSON data from a URL in a listview on an Android application using a straightforward parsing method

I need help with parsing a JSON response from a URL within my Android application... I've attempted several methods found online, but I'm unable to successfully parse it. The JSON content appears as follows: [ { "city_id": "1", ...

Is it possible to have an interface, function, and variable all sharing the same name in a declaration?

Is it possible to have an interface, function, and variable all with the same name? For example, I would like to define the function as follows: declare function someName(...args: any[]); someName('foo'); The interface would look like this: ...

Bring in numerous variables into a Gatsby component using TypeScript and GraphQL Typegen

import { graphql } from 'gatsby'; const Footer = ({phone}: { phone?: Queries.FooterFragment['phone'];}): JSX.Element => { return <footer>{phone}</footer>; }; export default Footer export const query = graphql` fragm ...

Transferring information between Puppeteer and a Vue JS Component

When my app's data flow starts with a backend API request that triggers a Vue component using puppeteer, is there a way to transfer that data from Backend (express) to the vue component without requiring the Vue component to make an additional backend ...

The asynchronous sorting feature in Mat Table, combined with MatPaginator, is currently experiencing issues. The datasource is being assigned asynchronously in

I have been attempting to incorporate matSort functionality into an existing MatTable, however, I am facing difficulties despite following the instructions from a related thread on mat-sort not working on mat-table. It seems like my issue might be due to t ...

Tips for understanding the encoding of an NSString in UTF-8

Currently, I'm utilizing SBJSONParser for parsing a JSON data retrieved from an API. In the fetched JSON data, the title is displayed as title = "F\U00c3\U00b6rdermittel";, which is already UTF-8 encoded by SBJSONParser. Ideally, the string ...

Launching a MEAN stack application on Heroku

My current challenge involves deploying an application I have developed using the MEAN stack on Heroku. The issue seems to be related to the structure of my application. All server-side code is contained in a directory named 'server', which inclu ...

Implementing Azure AD authentication with Angular and .NET Core 2 Web API

My goal is to implement authentication in my application using Azure AD Currently, the flow of my application looks like this: User -> AngularApp -> Azure Login -> AngularApp with token -> API Call to backend with token -> Backend verifies ...

What is the best way to view real-time updates on an Angular project?

Currently, I am working on an Angular project and typically use the command "ng serve" to run it. However, in comparison to Ionic where I can simply run "ionic serve" and view live updates of my code changes in the browser, I am wondering how I can achie ...

The function causes changes to an object parameter once it has been executed

I've encountered an issue with a function that is supposed to generate a string value from an object argument. When I call this function and then try to use the argument in another function, it seems to be getting changed somehow. Here is the code fo ...

Exploring Entries in Several JSON Arrays

In my current project, I have successfully generated JSON using JSON-Simple. Query: I am seeking guidance on how to extract specific elements like "Sentiment," "score," and "review" from this JSON array. Although I have referred to a helpful resource he ...

Issues with CORS functionality in Angular and NodeJS application causing disruptions

I am encountering issues with my Angular application that is Dockerized. When loading the application on Edge or Firefox, all the REST API requests needed to populate the homepage are not reaching the application. However, when I load the same page on Chro ...

What is the optimal way to organize OATH and views in a Grails RESTful client application?

Greetings! I am delving into the world of Groovy and Grails for the first time. My goal is to create a Grails Restful Client App (potentially a liferay portlet) that can fetch JSON data and present it elegantly in views while adhering to best practices. F ...