简体   繁体   中英

No 'Access-Control-Allow-Origin' header is present on the requested resource in angular 4/2

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.

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 →*

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM