In Angular 4 service, the requested resource does not have the 'Access-Control-Allow-Origin' header

I am currently utilizing a service that calls a URL where an image file is located. However, when the URL is called, an error appears in the console stating: Failed to load "my file url": No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. It seems that the issue arises only when trying to fetch this image file URL. I have attempted to measure the time before and after calling the URL, but this error persists. While installing a CORS extension provides a temporary fix, it is not an ideal solution. Can anyone assist me in resolving this error? I seem to be at a standstill with it. Here is the component code snippet:


import { Component } from '@angular/core';
            import { SpeedService } from './speed.service';
            import { Observable } from 'rxjs/Observable';
            import {Subject} from 'rxjs/Rx';
            @Component({
              selector: 'app-root',
              templateUrl: './app.component.html',
              styleUrls: ['./app.component.css']
            })
            export class AppComponent {
              title = 'app';
              speed:any;
              speedInMb:any;
              speedBps:any;
              speedKbps:any;
              uspeedInMb:any;
              uspeedBps:any;
              uspeedKbps:any;
              ping: number = 0;
              pingArray:number[];
              imgPath:string;
              showLoader:boolean;
              startTime:any;



                constructor(private httpObj:SpeedService){
                 this.imgPath = "../assets/speed/bg.png"; 
                 this.showLoader = false;
                }

                myButtonStyle = {

                    'background':'#FF6C5B', 
                    'color':'#fff', 
                    'padding':'5px 10px',
                    'font-weight':'bold',
                    'cursor':'pointer'
                }




                    getSpeed(){

                    let downloadSize = 46057148;
                    let bitsLoaded = downloadSize * 8;
                    this.startTime = (new Date()).getTime();

                    this.httpObj.getDownloadSpeed()
                            .subscribe(
                                response => {

                                    let endTime = (new Date()).getTime();

                                     let duration = (endTime - this.startTime) / 1000;
                                     this.speedBps = (bitsLoaded / duration).toFixed(2);
                                     this.speedKbps = (this.speedBps/1024).toFixed(2);
                                     this.speedInMb= (this.speedKbps / 1024).toFixed(2);


                                     console.log("speed in mbps:"+this.speedInMb);

                                },
                                error => {
                                    alert(error);

                                }
                            );
                }



            }


            and my service code is

            import { Http } from '@angular/http';
            import { Injectable } from '@angular/core';

            import { Observable } from 'rxjs/Observable';
            import 'rxjs/add/operator/catch';
            import 'rxjs/add/observable/throw';

            import {Subject} from 'rxjs/Rx';
            import 'rxjs/Rx';

            @Injectable()
            export class SpeedService{

            private downloadString:string;




            pingStream: Subject<number> = new Subject<number>();
            ping: number = 0;
            url: string = "http://google.com";

            constructor(private loginServ: Http) {
                 this.downloadString  = "image file url";
            }




                getDownloadSpeed(){

                return this.loginServ.get(this.downloadString)
                                         .catch(this.catchError);   
                }




                private catchError(error:Response){
                    return Observable.throw(error || 'some error occurred');
                }

            }

        and my html code is

        <table align="center" style="width:1024px;">
          <tr><td colspan="3" style="text-align:center; color:#fff; font-family:verdana;"><h1>Speedtest</h1></td></tr>
          <tr><td colspan="3" align="center"><img [src]="imgPath" class="img-responsive" /></td></tr>
          <tr><td colspan="3" style="text-align:center;">
            <span *ngIf="!showLoader" [ngStyle]="myButtonStyle" (click)="getAvarageSpeed()">START NOW</span>
            <span *ngIf="showLoader"><img [src]="'../assets/speed/loader1.gif'" [ngStyle]="{'width':'150px', 'height':'40px'}"></span>
          </td></tr>
          <tr><td colspan="3">&nbsp;</td></tr>
          <tr>

          <td style="text-align:center; color:#FFF;"><strong>DOWNLOAD</strong> : {{speedInMb}} Mbps</td>


          </tr>
          </table>

I am uncertain where I might be going wrong. If someone can identify whether the problem lies within the service or the server side, and suggest a possible solution in Angular, it would be greatly appreciated as I am struggling to pinpoint the issue.

Answer №1

Utilize proxying support by setting "changeOrigin": true. For more information, you can check out this Proxy To Backend link.

Give it a try!

            constructor(private loginServ: Http) {
                 this.downloadString  = "api"; //replace image url with this
            }

To use proxying support, create a proxy-config.json file with the following configuration:

  {
      "/api": {
         "target": "http://speedspot.speedspot.netdna-cdn.com/speedspot3000x3000.jpg",
         "secure": false
    }
      "changeOrigin": true
    }

Make sure to include this script in your package.json:

"scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.config.json"//add this script

After adding the script, run npm start and verify if it's functioning as expected.

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

Matching only the specified Records in an array of Typescript generic objects

Check out this demo: https://tsplay.dev/Nnavaw I am working with an array that has the following structure: Array<{ id?: string; text?: string; date?: Date; }> This conflicts with the current implementation: data: Array<Par ...

Error encountered in Typescript: The method date.getDate is not recognized as a

My goal is to retrieve the date from the first input control and the number of days from the other input controls, add them together, and assign the result to the third date control using TypeScript. However, I am encountering an error with the following c ...

Identical names found in typescript within a react project

Having an issue with my react project where I am seeing a lot of duplication errors in almost all files located in this directory: C:\Users[user]\AppData\Local\Microsoft\TypeScript\4.3\node_modules@types\ I suspect ...

Encountering Typescript issues following the transition from npm to pnpm

Currently, I am facing a challenge in migrating an outdated Angular JS project from npm to pnpm. The main issue I am encountering is related to typescript errors, particularly the error message that states: error TS2339: Property 'mock' does not ...

Adding attributes dynamically to input elements in a React render function

I currently have an input tag inside my render function which looks like this: <input id="time" type="time"> I am now looking to dynamically add the value attribute to it. Is there a way to achieve this in React? Thank you for your help in advance ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

The process of compiling and monitoring *two* Typescript packages, where one is reliant on the other

I'm in the process of creating a Typescript library located under src/ and sample files under examples/. The current directory structure is as follows: examples/ package.json exampleFiles.ts src/ index.ts package.json I am able to compil ...

Is the ng bootstrap modal within Angular failing to show up on the screen

In the midst of working on my project, I encountered an issue with opening a modal using ng bootstrap. Although I found a similar thread discussing this problem, it did not include bootstrap css. I decided to reference this example in hopes of resolving t ...

Text that adjusts its size based on the available space between columns within a row

I am currently developing an application using angular and bootstrap, and I have a requirement to insert a link between two columns in the third row of iteration. Here is what I have attempted so far: Html: <div class="container"> <div clas ...

unable to find user in passport js deserialize function due to undefined variable

I've encountered an issue while working on the backend for a web application, specifically with passport. Currently, I can successfully register a user and log them in, but I'm facing a problem where I cannot log in twice in a row. Each time dese ...

While using Angular CLI on GitLab CI, an error occurred indicating that the custom rule directory "codelyzer" could not be

ng lint is throwing an error on Gitlab CI stating: An unhandled exception occurred: Failed to load /builds/trade-up/trade-up/common/projects/trade-up-common/tslint.json: Could not find custom rule directory: codelyzer. The strange thing is that ng lint ru ...

Is it possible to refresh the webpage in Angular when the tab is clicked?

Can someone help me find a solution to reload an Angular app's page when the user selects the browser tab? I've been exploring using window.location.reload() for this purpose, but I need guidance on triggering it specifically when the tab is sel ...

Adjusting the interface of a third-party TypeScript library

I am currently working on modifying a third-party interface. I'm curious about why this particular code is successful: import { LoadableComponentMethods as OldLoadableComponentMethods } from '@loadable/component'; declare module "load ...

Unveiling Angular library dependencies

Is there a way to conceal internal dependencies when developing an angular library? For example, during the development of my library, I added this dependency: yarn add moment-es6 However, I want to keep this as only an internal dependency and not impos ...

Angular form grouping radio buttons in a unique way

Encountering some unusual behavior with radio buttons and forms currently. In my form, I have 4 radio buttons set up. The issue I'm facing is that when I click on a radio button, it remains enabled permanently. This means I can have all 4 options sel ...

What is the purpose of the @NgModule annotation in Angular Material?

I've been struggling with using Angular-Material Components in different components. Despite watching and reading various tutorials, I still can't seem to get them to work. The error message I keep encountering is: compiler.js:2430 Uncaught Erro ...

Eliminate private TypeScript class properties from an object by using Vue 3's ref and reactive features

When an object with private properties or methods is passed to ref() or reactive(), the resulting proxy no longer contains the private properties. Consider the following class: class Pirate { name: string; age: number; private dream : st ...

Unraveling a Map Object via an HTTP Request in Angular

I'm facing a puzzling issue. When I was using Angular 9.1, I had no problem sending a Map<string, string[]> through a request. However, after upgrading to Angular 13, this feature suddenly stopped working. Strangely, I couldn't find any inf ...

The specified object is not extensible, hence the property effectTag cannot be added

Upon launching the React application, it initially renders perfectly, but after a few seconds, an error occurs that I am unable to debug. The error is being shown in node_modules/react-dom/cjs/react-dom.development.js:21959. Can anyone provide assistance ...

What are some alternatives for integrating React production build files apart from utilizing Express?

Is there a way to integrate React into my library using the HTTP module? I'm trying to figure out how to recursively send static files. Specifically, I want to include the build folder from the React production build, but I'm not sure how to go a ...