首页 > 解决方案 > Angular 表单数据上传到 Cloudinary 时出现 Cors 错误

问题描述

您好我正在尝试从我的 localhost 角度应用程序将图像上传到 cloudinary api 并收到以下错误

从源“http://localhost:4200”访问“https://api.cloudinary.com/v1_1/xxxxxx/image/upload”的 XMLHttpRequest 已被 CORS 策略阻止:访问不允许请求标头字段类型预检响应中的 -Control-Allow-Headers。

我的角度形式和 http 请求:

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

标签: angularcors

解决方案


对于这个问题,有三种解决方案:

  1. 从服务器端禁用 cors 策略
  2. 在浏览器中禁用 cors,例如 google chrome https://alfilatov.com/posts/run-chrome-without-cors/
  3. 创建一个代理文件并通过它连接到服务器

代理.json

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

环境.ts

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

并使用以下命令运行角度

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

推荐阅读