1
votes

Hi I am trying to upoload images to cloudinary api from my localhost angular application and get the following error

Access to XMLHttpRequest at 'https://api.cloudinary.com/v1_1/xxxxxx/image/upload' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field type is not allowed by Access-Control-Allow-Headers in preflight response.

My angular form and http request :

<input type="file" #file (change)="onChange(file.files)" multiple />
onChange(files: FileList) {
    this.files = Object.values(files);

    const headers = new HttpHeaders({
      'Content-Type': 'multipart/form-data',
      'Accept': 'application/json',
      'Type': 'formData'
    });

    for (let file of this.files) {
      var data = new FormData();
      data.append('file', file);
      data.append('upload_preset', 'pics');

      this.http
        .post(
          'https://api.cloudinary.com/v1_1/xxxxxxxx/image/upload',
          file,
          {
            headers
          }
        )
        .subscribe(
          resData => {
            console.log(resData);
          },
          errorMessage => {
            console.log(errorMessage);
          }
        );
    }
  }
2
What happens if you remove the 'Type': 'formData' header setting from your frontend JavaScript code? - sideshowbarker
Removing the complete header information worked! Looks like angular configured the header information? - Revanth Bysani

2 Answers

0
votes

There is three solution for this issue:

  1. disable cors policy from server-side
  2. disable cors in the browser, for example for google chrome https://alfilatov.com/posts/run-chrome-without-cors/
  3. create a proxy file and through that connect to the server

proxy.json

  "/api/**": {
    "target": {
      "host": "https://api.cloudinary.com/v1_1/xxxxxxxx/image/upload",
      "protocol": "https:",
      "port": 80
    },
    "secure": false,
    "changeOrigin": true,
    "logLevel": "info"
  }

environment.ts

export const environment = {
  production: false,
  apiUrl: '/api/alpha/v1',
};

and run angular with below command

ng serve --proxy-config proxy.json -o
0
votes

CROS Cross Origin Issue - unable to connect with database When API is called -> request is unable to reach API server

usually in Case when some API method requires 2 parameters (name,image) but in angular application we called Post method & passed single parameter to it (name)

Here for images Upload/Update - postImages() - no header Content-Type instead of post()

DONT stringify image -> bytes will be lost (Make new Post route:postImages)

dataService:

enter image description here

header_interceptor:

enter image description here

Component calling API (upload image + add name from Form -> API)

enter image description here