Angular向外部API发POST请求传base64时跨域被阻止如何修复
核心问题原因
- 你在请求头中添加的
Access-Control-Allow-Origin: *是错误用法:该响应头由服务端返回时才生效,前端主动在请求头中添加该字段,会触发跨域预检规则,反而导致请求失败。 - 你将本地图片转成base64字符串后传给接口,DeepAI的接口会将该字符串识别为跨域资源地址,因此触发跨域报错;传公共可访问的图片链接时,接口走服务端拉取资源的逻辑,不会触发跨域。
修复步骤
方案1(推荐:无需转base64,性能更优)
直接将选中的文件对象传入FormData即可,不需要做base64转换,修改后的代码如下:
HTML代码(无需改动)
<input type="file" id="readImg" (change)="upload()" accept="image/jpeg, image/png">
TypeScript代码
styleImage: string; contentFile: File | null = null; constructor(private http: HttpClient) {} ngOnInit() { this.styleImage = 'https://afremov.com/images/product/image_938.jpeg'; } upload(){ // 处理图片上传,直接存储File对象 const upload = document.getElementById('readImg') as HTMLInputElement; if(upload.files?.[0]){ this.contentFile = upload.files[0]; this.apiCall().then(); } } async apiCall(){ // 调用外部接口 const url = 'http://api.deepai.org/api/fast-style-transfer'; const headers = new HttpHeaders() .set('accept', 'application/json') .set('api-key', 'myKey'); // 替换为你的实际api-key const requestBody = new FormData(); requestBody.append('content', this.contentFile as Blob); requestBody.append('style', this.styleImage); const resp: any = await this.http.post(url, requestBody, { headers: headers }).toPromise(); console.log(resp.output_url); }
方案2(必须使用base64的场景)
如果你的业务逻辑必须先拿到base64做其他处理,需要先将base64转换为Blob对象再传入FormData:
base64转Blob工具方法
function base64ToBlob(base64Str: string, mimeType: string = 'image/jpeg'): Blob { const base64Data = base64Str.split(',')[1]; const byteCharacters = atob(base64Data); const byteArrays: Uint8Array[] = []; for (let offset = 0; offset < byteCharacters.length; offset += 512) { const slice = byteCharacters.slice(offset, offset + 512); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } byteArrays.push(new Uint8Array(byteNumbers)); } return new Blob(byteArrays, { type: mimeType }); }
调用示例
在apiCall方法中,将转换后的Blob传入FormData即可:
const contentBlob = base64ToBlob(this.contentImage.src); requestBody.append('content', contentBlob);
内容的提问来源于stack exchange,提问作者COM
相关产品推荐
相关产品推荐

