0

Hi i am using angular js version 5.2.6. and i am trying to hit a url through service. this url is a image url. means if you click on this url you will get an image file and nothing more than this. i want to know the time taken in hitting that url. when i hit the url i get an error No 'Access-Control-Allow-Origin' header is present on the requested resource. i can not do any thing in server side. and in client side i am using proxy.config.json file which contain following code.

{
      "/api": {
         "target": "image file url",
         "secure": false
    },
      "changeOrigin": true
}

and then i modify my code in package.json file

{"start": "ng serve --proxy-config proxy.config.json"}

but this is also not working. finely i tried using JSONP. but it is giving error for MIME type for image. Here is my component code

import { Component, OnInit} from '@angular/core';
import { SpeedService } from './../speed.service';
import { Observable } from 'rxjs/Observable';
import {Subject} from 'rxjs/Rx';
@Component({
  selector: 'speedtest-app',
  templateUrl: './speedtest.html',
  styleUrls: ['./speedtest.css']
})
export class SpeedtestComponent implements OnInit{
  title = 'app';
  speed:any;
  speedInMb:any;
  speedBps:any;
  speedKbps:any;
  ping: number = 0;
  pingArray:number[];
  imgPath:string;
  showLoader:boolean;
  startTime:any;
  uploadEndTime:any;
  avarageDownloadArray:any[];
  avarageDownloadSpeed:number;


  pingStream: Subject<number> = new Subject<number>();

    constructor(private httpObj:SpeedService){

     this.imgPath = "../assets/speed/bg.png"; 
     this.showLoader = false;
     this.gaugeValue = 0;
     this.uploadText = false;
     this.downloadText = false;
     this.showGauge= true;
     this.gauzeText = "Start Now";
     this.gazeRes = false;

    }

        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);
                         this.getUploadSpeed();


                    },
                    error => {
                        alert(error);

                    }
                );
    }

}

and my service code is

import { Http, Headers, Response, RequestOptions, RequestMethod } 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;

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');
    }

}

I am stuck on this problem form last 20 days and not able resolve this issue. Please Please Pleas some one help me . I am not able to get the exact solution. I have also tried a temporary solution to install CORS extension. that works. but i know that it is not the correct solution. Plesae some one tell me what should i do. i am completely frustrate from this problem.

2 Answers2

1

You have to add some headers in server file.It is not a angular error.

You need to add below lines in your server file.

access-control-allow-credentials →true

access-control-allow-headers →Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With

access-control-allow-methods →POST,GET

access-control-allow-origin →*

BalaDev
  • 193
  • 1
  • 2
  • 11
  • `i can not do any thing in server side`. –  Mar 13 '18 at 12:54
  • May be this will helpful.try this: https://stackoverflow.com/questions/46126844/no-access-control-allow-origin-client-side-fix?rq=1 – BalaDev Mar 13 '18 at 13:43
0

CORS issues are usually corrected on the server, not on Angular.

While coding though, you can bypass the issue with a proxy, as you did. But you should use this for the code of the proxy

{
  "/api": {
    "target": "http://localhost:4000",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

This will show you the logs in your console and bypass CORS issues.

To make HTTP requests in your code, you will use

this.http.get('/api/image/123');

This will call http://localhost:4000/api/image/123

EDIT to calculate the load time of an image :

<img [src]="src" #image>

In your component

src = 'www.something.com/images/filename.jpeg';
@ViewChild('image') img: ElementRef;

ngOnInit() {
  console.time('imageLoad');

  this.img.nativeElement.onload = () => {
    console.timeEnd('imageLoad');
  };

  this.img.nativeElement.src = this.src;
};
  • this time i am getting 404 error. trichetriche one thing which i forgot to clear that my server address is localhost:4000(local address). and myimage file is located on another live server. suppose my image file is located on www.something.com/images/filename.jpeg. but when i pass `{ "/api": { "target": "www.something.com", "secure": false, "changeOrigin": true, "logLevel": "debug" } }` – vimlesh yadav Mar 13 '18 at 10:38
  • Your image isn't the issue. HTML can load images without problem. Your issue is that Ajax calls can't go no another domain. I edit my answer to take your real address into configuration, please take a look –  Mar 13 '18 at 10:41
  • wait trichetriche let me complete first what i have done. – vimlesh yadav Mar 13 '18 at 10:46
  • and when i pass service url `this.loginServ.get('/images/filename.jpeg')`. then it gives a 404 error. because it try to access on localhost:4200/images/filename.jpeg and my file is located www.something.com/images/filename.jpeg – vimlesh yadav Mar 13 '18 at 10:48
  • You don't request an image with an HTTP call ... This is supposed to be the source of an image. –  Mar 13 '18 at 11:35
  • thank trichetriche for your valuable reply but what should i do in this case if i have to calculate the time taken to read an image file. – vimlesh yadav Mar 13 '18 at 12:25
  • thank you trichetriche for your answer. i will try this code and update accordingly – vimlesh yadav Mar 13 '18 at 12:51
  • No problem, but it's getting kind of long, if you update your code notify me with the new question, I will make another answer on this post –  Mar 13 '18 at 12:55
  • Hi Trichetriche it is giving error "Cannot find name 'ViewChild'." when i placed above code in component. – vimlesh yadav Mar 13 '18 at 13:50
  • You need to import it from `@angular/core`, along with ElementRef –  Mar 13 '18 at 13:50
  • Thanks Trichetriche it working now. but i have problem that i want to calculate internet speed (download/upload). but in this case result is not satisfactory. Do you have any solution to get internet speed(download/upload) in angular 2/4. – vimlesh yadav Mar 13 '18 at 14:00
  • **[There is already a question for that](https://stackoverflow.com/questions/5529718/how-to-detect-internet-speed-in-javascript)**, if you want to take a look –  Mar 13 '18 at 14:01
  • yes it is. but i dont know its typescript implementation. and that is why not able to implement that code in angular 2/4 – vimlesh yadav Mar 13 '18 at 14:04
  • hi trichetriche can you please help me to how to write code to calculate internet upload/download speed in angular 2/4. please help me i am new on angular. when i past the above javascript code it was giving lot of syntax error. – vimlesh yadav Mar 17 '18 at 06:15
  • Download something, get its size, and see how much time it took with `console.time` and `console.timeEnd`, then calculate –  Mar 17 '18 at 09:17