Tips for resolving the "Access-Control-Allow-Origin" problem in Angular2 with Lite-Server

I am working on an Angular 2 application that interacts with an external API to fetch data.

Unfortunately, I do not have the authority to modify the API code. However, I can make changes to the TypeScripts and Lite-Server configuration.

Encountered Error: XMLHttpRequest cannot load .... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.

I have researched CORS extensively but I am unsure how to integrate it into my code. What would be the simplest way to resolve this issue?

Here is my service:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Page } from './page';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class ProductService {

    private urlPage = 'http://api.zanox.com/json/...';

    constructor(private http: Http) { }

    getPage(): Observable<Page> {
        return this.http.get(this.urlPage).map(this.extractData).catch(this.handleError);
    }

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

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

This is my component:

import { Component, OnInit } from '@angular/core';
import { ProductService } from './product/productService';
import { Page } from './product/page';

@Component({
    templateUrl: 'app/app.product.html',
    selector: 'product-app',
    providers: [ProductService]
})
export class AppProduct implements OnInit {

    private errorMessage: string;
    page: any;

    constructor(
        private productService: ProductService) {
    }

    ngOnInit() {
        this.getPage();
    }

    getPage() {
        this.productService.getPage().subscribe(
            page => this.page = page,
            error => this.errorMessage = <any>error
        )
    }
}

Answer №1

My solution to the problem involved utilizing JSONP:

In my app.module.ts file, I made sure to include the following code snippet:

import { JsonpModule } from '@angular/http';

@NgModule({
    imports: [JsonpModule]
})

Within my productService.ts file, I added the necessary code for JSONP functionality:

import {Jsonp} from '@angular/http';

private urlPage = 'http://api.zanox.com/json/...&callback=JSONP_CALLBACK';

constructor(private _jsonp: Jsonp) {}

getPage(): Observable<Page> {
    return this._jsonp.get(this.urlPage).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

Variety of type 'class' in Typescript

My goal is to achieve the following: createClass(c:class):SomeInstance { return new class() as SomeInstance; } But I encounter an error that says 'type expected' when I specify the :class part. ...

Error: Unable to access the 'registerControl' property of the object due to a type mismatch

I'm struggling to set up new password and confirm password validation in Angular 4. As a novice in Angular, I've attempted various approaches but keep encountering the same error. Seeking guidance on where my mistake lies. Any help in resolving t ...

Is it possible to use ng-bootstrap with vertical tabs?

I'm experimenting with displaying ng-Bootstrap tabs vertically, but the provided example doesn't quite fit my needs. I'm envisioning a layout similar to what I've sketched in the diagram. Do you think it's achievable? Any suggestio ...

In TypeScript, what specific term denotes a type of data?

Given the following code snippet: class Foo { } interface TypeProvider() { type(): ?; } class Bar implements TypeProvider { type(): ? { return (Foo); } } class Baz implements TypeProvider { type(): ? { return (Bar); ...

Tips for resolving the error message "What to do when reportWebVitals can't be located

Having some trouble with importing reportWebVitals for my React 18 application that is based on WebPack 5. Below is a snippet of my index.tsx file: import React from 'react'; import ReactDOM from 'react-dom/client'; import './style ...

The logs of both the frontend and backend display an array of numbers, but surprisingly, this data is not stored in the database

I am attempting to recreate the Backup Codes feature of Google by generating four random 8-digit numbers. for(let i = 0; i < 4; i++) { let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000); backendCodes.push(back ...

Angular element fails to display properly

I'm currently working on developing a website using Angular and creating a header component. To generate the necessary files, I used the command ng g c commons/header which creates the HTML, SCSS, TS, and .spec.ts files. I then made modifications to t ...

Issue with Angular 2: Observable and Subscription not activating

In my app, I have encountered a situation where calling a method in a service from Component A does not trigger the subscribed Component B. The subscribe() function is not working as expected. The issue at hand: Despite having successfully performed this ...

Resolving the "Abstract type N must be an Object type at runtime" error in GraphQL Server Union Types

Given a unique GraphQL union return type: union GetUserProfileOrDatabaseInfo = UserProfile | DatabaseInfo meant to be returned by a specific resolver: type Query { getUserData: GetUserProfileOrDatabaseInfo! } I am encountering warnings and errors rel ...

Steps to implement Angular routerLink on an image for seamless navigation to a different component

Is there a way to create an interactive image that leads to other sections within Angular? The intention is for this particular image to serve as a miniature profile picture of the existing user, located in the navigation bar. <img ngSrc="{{User.photo ...

What is the best way to invoke a function in a specific child component from its parent component?

It seems that I might have provided too much information, but the main question remains: how can I call a method in the child component from the parent template's click() event. <button(click)='get()'>GET</button> In my case, th ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

Turning Typescript into Javascript - the How-To Guide

Currently following Shopify's Node Api tutorial to implement a Redis store in my project. The tutorial provides code in typescript, but my entire project is in javascript (React/nextjs). I've been struggling to convert the code to javascript for ...

Searching for similar but not identical results using Knex.js

I am seeking a solution to retrieve similar posts without including the post itself. Here is my approach: export async function getSimilars(slug: string) { const excludeThis = await getBySlug(slug) const posts = await knex('posts') .whe ...

Changing Angular Material datepicker format post form submission

After selecting a date, the input field is populated with a format like DD/MM/YYYY Now, when attempting to send this data through a form and logging it in my component, datapicker.component.ts onFindAWhip(form: NgForm){ const value = form.value; ...

Creating custom TypeScript validation types at compile time

Is it possible to create custom type definitions in TypeScript that are only checked during compile time? I want users to define a value for a variable (that won't change at runtime) and validate if it meets certain criteria. For example, requiring a ...

Issue with Async pipe when utilizing autocomplete functionality

HTML Code <mat-form-field> <input type="text" matInput class="formControl" [formControl]="name" [matAutocomplete]="auto" > <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of city | async" [valu ...

Is it possible to retrieve a value obtained through Request.Form?

Within my Frontend, I am passing an Object with a PersonId and a FormData object. const formData = new FormData(); for (let file of files){ formData.append(file.name, file,); } formData.append('currentId',this.UserId.toString()); const upl ...

Encountering an issue with Angular 8 and Material where a table does not fully render on mobile browsers like Chrome, causing rows to only half

Currently, I have an Angular 8 application integrated with Material v8.2.3 where a table with expanding rows is being used. While everything functions perfectly on desktop browsers, there seems to be an issue when accessing the application on mobile phone ...

Angular: Object contains data, but its properties have not been defined

I am encountering an issue while trying to access properties of the Dto object filled from my rest service, as they are coming up undefined. Firstly, I fetch the data: this.mapservice.getAllCoordinates().subscribe((data: CoordinateDto[]) => { this.co ...