angular - 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);
}
);
}
}
解决方案
对于这个问题,有三种解决方案:
- 从服务器端禁用 cors 策略
- 在浏览器中禁用 cors,例如 google chrome https://alfilatov.com/posts/run-chrome-without-cors/
- 创建一个代理文件并通过它连接到服务器
代理.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
推荐阅读
- angular - 循环中按索引的角度调用数组
- php - 按用户计数整数值和顺序
- ios - 如何从 UIViewController 调用 AppDelegate 方法
- javascript - 使用 dropzone 和 laravel 更新多个图像
- sql - 在 BigQuery 中,我可以添加缺失数据的行吗?
- sql - 缺少 sqldeveloper Oracle 的 TNS 文件
- seaborn - 如何使用 Seaborn 绘制单列?
- sql - MVC 应用程序不使用 EntityFramework 显示数据库记录
- r - 如何将这两个图表组合成一个堆叠条形图?(以百分比显示计数)
- sql - 将运算符与 unix_timestamp 混合会产生意外的 null