Home > database >  How to fix Cross-Origin Request Block in angular when making a post request to an external api call
How to fix Cross-Origin Request Block in angular when making a post request to an external api call

Time:10-14

I have the following post request that im making to an external api : The request works when i pass 2 links to images but when i pass the base64 string of an image i get a Cross-Origin error this is my code:

Html:

   <input type="file" id="readImg" (change)="upload()" accept="image/jpeg, image/png">
styleImage: any;
contentImage: any;

 constructor(private http: HttpClient) {}

 ngOnInit() {
   this.styleImage = 'https://afremov.com/images/product/image_938.jpeg';
}

 upload(){ //function to hangle image upload and get base64 string
     const upload = document.getElementById('readImg') as HTMLInputElement;
     if(upload.files[0]){
      const reader = new FileReader();
      this.contentImage = new Image();

      reader.readAsDataURL(upload.files[0]);

      reader.addEventListener('load', (event) => {
        this.contentImage.src = event.target.result as string;

        console.log('contentImage: '   this.contentImage.src);

    apiCall().then();
}

 async apiCall(){ //function to call the external epi
      const url = 'http://api.deepai.org/api/fast-style-transfer';
      const headers = new HttpHeaders()
        .set('accept', 'application/json')
        .set('Access-Control-Allow-Origin', '*')
        .set('api-key', 'myKey');

      const requestBody = new FormData();

      requestBody.append('content', this.contentImage.src);
      requestBody.append('style', this.styleImage);

      const resp: any = await this.http.post(url, requestBody, {
        headers: headers
      }).toPromise().then();

      console.log(resp.output_url);
}

CodePudding user response:

If you use the developer console to inspect the request that is sent when calling the API here: https://deepai.org/machine-learning-model/fast-style-transfer, you'll see that a File object rather than a data URL is being appended to the FormData object.

You should be able to skip the FileReader and use the File object directly:

const file = document.getElementById('readImg').files[0]; requestBody.append('content', file);

  • Related