Mozilla struggles to interpret JSON data

When using Angular2 (RC4), I utilize this code snippet to retrieve data from my WebApi:

getAppointment(id: number): Observable<Event> {
    return this._http.get(this._serviceUrl + 'get/' + id)
        .map(this.extractData)
        .catch(this.handleError);
}

The function this.extractData looks like this:

private extractData(res: Response) {
        let body = res.json();
        return body || {};
}

Everything works fine in Chrome, IE, Edge, but when it comes to Mozilla, it throws this error:

JSON.parse: unexpected character at line 1 column 1 of the JSON data

This issue seems to be related to the @angluar2/http module static_response.d.ts file.

/**
 * Attempts to return body as parsed `JSON` object, or raises an exception.
 */
json(): any;

And in the static_response.d.js file:

/**
 * Attempts to return body as parsed `JSON` object, or raises an exception.
 */
Response.prototype.json = function () {
    var jsonResponse;
    if (http_utils_1.isJsObject(this._body)) {
        jsonResponse = this._body;
    }
    else if (lang_1.isString(this._body)) {
        jsonResponse = lang_1.Json.parse(this._body);
    }
    return jsonResponse;
};

Why does this fail in Mozilla? Could it be a bug in @angular2/http?

Answer №1

I encountered the same issue as well.

Fortunately, I was able to resolve it by adjusting the settings in my browser and it actually worked.

Here's a workaround that may help:

1. Open about:config in a new tab on Firefox.

2. Look for Network.http.accept.default.

3. Original value: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8

4. New value: text/html,application/xhtml+xml,application/JSON;q=0.9,/;q=0.8

Answer №2

Due to the length of my response, I have turned this into an answer instead of a comment - I will delete it if it doesn't work.


To ensure you receive a JSON response instead of XML, consider explicitly setting the Accept header in your code like this:

getAppointmentInfo(id: number): Observable<Event> {
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });

    return this._http.get(this._serviceUrl + 'get/' + id, options)
        .map(this.extractData)
        .catch(this.handleError);
}

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

Angular sending data to ASP.NET MVC results in null object properties

My issue involves sending data from Angular (v15) to ASP.NET on the .NET Framework 4.72. On the client side: var name = this.inName; var queue = new Queue(); queue.QueueId = 6; queue.CustomerFullName = name; queue.Status = 5; var d = new Date(); const da ...

Enhancements to managing universal configuration object across the entire application

My current project involves working on an application with multiple products. To streamline product-specific configuration and eliminate the need for excessive if-else statements, I am looking to implement product-specific config keys that are consistently ...

I'm facing issues with the angular-stl-model-viewer in my current Angular project

I recently attempted to incorporate an stl-viewer into my Angular project using the npm package angular-stl-model-viewer and managed to install all necessary dependencies without any issues. However, I encountered a problem where the viewer is not displayi ...

Issue encountered while attempting to remove a post from my Next.js application utilizing Prisma and Zod

Currently, I'm immersed in a Next.js project where the main goal is to eliminate a post by its unique id. To carry out this task efficiently, I make use of Prisma as my ORM and Zod for data validation. The crux of the operation involves the client-sid ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Is it necessary to use Generics in order for a TypeScript `extends` conditional type statement to function properly?

Looking to improve my understanding of the extends keyword in TypeScript and its various uses. I recently discovered two built-in utilities, Extract and Exclude, which utilize both extends and Conditional Typing. /** * Exclude from T those types that are ...

Arranging unit tests can be a headache in Angular using Jasmine

I'm finding it really challenging to set up the testing module for my unit tests in Angular. The issue I'm facing is that I struggle to identify all the dependencies I need. My current approach is to start karma with ng test and then check the e ...

What is the process for transferring a function to reducers in Redux Toolkit?

In one of my files called Main.tsx, I have a function that sends a request and retrieves data: async function fetchProducts(productsPage = 1, id?: number) { const itemsPerPage = 5 let url: string if (id) { url = `https://reqres.in/api/ ...

Having trouble transitioning to Angular2 RC? Let's chat at [email protected] - we can help!

I encountered an error while attempting to upgrade angular2 to RC. Due to JWT dependencies on RC, I had to switch to @angular. M:\workspace\Angular2StartKit>npm install npm ERR! addLocal Could not install M:\workspace\Angular2StartK ...

Unexpected identifier error: Typescript interface name syntax is incorrect

I am currently learning Typescript and still navigating my way through it. I have extensively searched for a solution to the issue I am facing, but couldn't find one, hence I am seeking help here. The problem lies in a SyntaxError at the interface nam ...

Caution in version 3.5.1 of Vue Router: The tag prop of `<router-link>` is now obsolete and has been eliminated in Vue Router 4

After updating the node packages of our Vue.js app, a warning is now appearing in the browser console: [vue-router] The 'tag' prop has been deprecated and removed in Vue Router 4. To remove this warning, use the v-slot API. Check out the migrat ...

Having trouble with Nextjs API Integration - encountering error 404

I'm currently facing a major issue and I've hit a dead end. I've been spending days trying to connect my local nextjs 14 app to the CVENT API, but I keep receiving a persistent 404 error. Here's what is displayed in the frontend console ...

Exploring the world of Ionic and Angular on Coursera

I've been following a Coursera tutorial, but I've encountered an error. Although I have the code provided by the teacher, it's not working as expected. Unfortunately, I am unsure of what additional code to include since everything seems to ...

Utilizing Ionic 2 with Typescript for executing forEach operations

I am in the process of migrating my AngularJS application to Angular 2. In my AngularJS controller, I had a JSON array that I was iterating through to display data in an accordion list. Now, I need to implement the same functionality in my Angular 2 compon ...

Guide on how to switch a class on the body using React's onClick event

There's a button in my code that triggers the display of a modal-like div element. When this button is clicked, I aim to apply a class to the body element; then when the close button is clicked, I'll remove this class. I'm looking for guid ...

"What is the best way to specify a type for the src attribute in a tsx file within a

<Image src= { sessionData?.user.image} alt="user" width={100} height={100} />` An issue has been encountered: There is a type error stating that 'string | null | undefined' cannot be assigned to type 'stri ...

`Why Lazy Loading Modules in Angular2(RC-6) is Not Possible`

In my Angular2 application, I am working on implementing lazy loading for feature modules. The application consists of a root module and two feature modules. The paths for the root module and its routing files are: app/public/scripts/app.module.ts app/pu ...

Ways to adjust height dynamically to auto in React

I am currently stuck on a problem concerning the adjustment of my listing's height dynamically from 300 to auto. My goal is to create a post-like feature where users can click "read more" to expand and view the full post without collapsing it complete ...

Determine whether an element is visible following a state update using React Testing Library in a Next.js application

I'm looking to test a NextJS component of mine, specifically a searchbar that includes a div which should only display if the "search" state is not empty. const SearchBar = () => { const [search, setSearch] = useState(""); const handleSear ...

The compatibility issue arises when trying to utilize Axios for API calls in Ionic 6 React with react-query on a real Android device in production. While it works seamlessly on the emulator and browser

My form utilizes react-hook-form to submit data to a server. Here is the code: <FormProvider {...methods}> <form onSubmit={handleSubmit(onIndividualSignup)}> <Swiper onSwiper={(swiper) => setSlidesRef(s ...