嗨,我正在尝试将图像从本地Angular应用程序上载到cloudinary api并出现以下错误
CORS策略已阻止从来源“ http:// localhost:4200”访问“ https://api.cloudinary.com/v1_1/xxxxxx/image/upload”处的XMLHttpRequest:请求标头字段类型不是在飞行前响应中被Access-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);
}
);
}
}
答案 0 :(得分:0)
此问题有三种解决方案:
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',
};
并使用以下命令运行角度
ng serve --proxy-config proxy.json -o
答案 1 :(得分:0)
CROS 跨域问题 - 无法连接数据库 调用 API 时 -> 请求无法到达 API 服务器
通常在某些 API 方法需要 2 个参数(名称、图像)的情况下 但是在 Angular 应用程序中,我们调用了 Post 方法并将单个参数传递给它(名称)
这里是图片上传/更新 - postImages() - 没有标题 Content-Type 而不是 post()
不要对图像进行字符串化 -> 字节将丢失(创建新的 Post 路由:postImages)
数据服务:
header_interceptor:
组件调用API(上传图片+从Form添加名称-> API)