-1

Hi i am using a service that is hitting a url on which a image file is placed.but when it hit the url it gives the error in console. 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 is just hitting that image file url. and i am trying to calculate the time before and after hitting the url. but it is giving above errorr. i am not getting exact solution. there is an temporary solution after installing CORS extension but it is not perfect way to handle it. Please help me to remove that error. i am completly stuck on it. Here is my component code

            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 don't know that where i am doing mistake. Please some tell me that is it problem of service(client side) or server. is there any solution in angular. because on server side i am doing nothing just hitting the URL and nothing. i am not getting anything in response also which can create problem.
Irshad
  • 35
  • 2
  • 7
  • this is generally a server-side issue, check here https://stackoverflow.com/questions/48184107/read-response-headers-from-api-response-angular-5-typescript/48184742#48184742 – Hrishikesh Kale Mar 01 '18 at 11:34
  • yes..,it is server side issue..,can you provide us with little bit more about your server side code ? – cantona_7 Mar 01 '18 at 12:40
  • i am doing nothing in server side. i am just hitting this url http://speedspot.speedspot.netdna-cdn.com/speedspot3000x3000.jpg. to get the time taken in reading that image file – Irshad Mar 01 '18 at 12:46
  • Possible duplicate of [XMLHttpRequest cannot load https://www.\[website\].com/](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-https-www-website-com) – Quentin Mar 05 '18 at 16:22

1 Answers1

0

Use proxying support and set "changeOrigin": true Refer this link Proxy To Backend.

Try this out

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

use proxying support, create a proxy-config.json with below configuration

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

in your package.json

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

Run npm start and see if its working.

Vikas
  • 11,859
  • 7
  • 45
  • 69
  • what did you do? could you share your proxy.config.json/.js – Vikas Mar 05 '18 at 15:45
  • yes vikas my file name is proxy.config.json and code is `{ "/api": { "target": "http://speedspot.speedspot.netdna-cdn.com/speedspot3000x3000.jpg", "secure": false }, "changeOrigin": true }` – Irshad Mar 06 '18 at 07:27
  • `{ "name": "speed-app", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve --proxy-config proxy.config.json", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, ` – Irshad Mar 06 '18 at 07:34
  • Vikas please tell me if i am doing any thing wrong. – Irshad Mar 09 '18 at 10:58
  • [Plugin](https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en), see if this works. – Vikas Mar 09 '18 at 11:24
  • Thanks Vikas it is working. but i can not ask client to add this plugin. – Irshad Mar 09 '18 at 11:37
  • Modifying the server to add the header Access-Control-Allow-Origin: * is one of the solutions, but it doesn't seem possible in your case. secondly, usage of proxying support in client-side solves this issue and last approach was using plugin, apart from this try adding header to get request [Here](https://stackoverflow.com/questions/36002493/no-access-control-allow-origin-header-in-angular-2-app/38807337) and disable the plugin – Vikas Mar 09 '18 at 12:03