You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Angular向Node.js后端上传文件?前端请求报错求助

文件上传前端调用问题排查与解决

我用Node.js开发后端文件上传接口,经Postman测试功能正常,但前端调用时后端报错,检查代码未发现明显问题,求技术建议。

前端代码片段

按钮HTML代码

<input type="file" style="display: inline-block;" (change)="onFileChange($event.target.files)" placeholder="Upload file" accept=".xlsx">

onFileChange方法

onFileChange(event: File[]) {
    this.commonAPIService.postFile(event[0]).subscribe(data => {
    }, error => {
        console.log(error);
    });
}

服务层代码

postFile(fileToUpload: File) {
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    return this._http.post('/api/single', formData).pipe(
        map(() => {
            return true;
        }),
        catchError((err) => throwError(handleError(err)))
    );
}

后端报错信息

SyntaxError: Unexpected token - in JSON at position 0


问题分析与解决

这个报错说明后端在尝试解析JSON格式的请求体,但前端实际发送的是multipart/form-data格式的FormData,导致解析失败。

原因在于Angular的HttpClient默认会为POST请求设置Content-Type: application/json请求头,后端收到这个头后会尝试按JSON解析请求体,但FormData是多部分表单格式,自然解析失败。而Postman测试时会自动正确设置请求头,所以能正常工作。

解决方法很简单:在发送POST请求时,让浏览器自动处理multipart/form-data的请求头,不要手动指定或保留默认的JSON头。修改服务层代码如下:

postFile(fileToUpload: File) {
    const formData: FormData = new FormData();
    formData.append('fileKey', fileToUpload, fileToUpload.name);
    // 配置headers,让浏览器自动生成正确的multipart请求头
    const headers = new HttpHeaders({ 'Content-Type': undefined });
    return this._http.post('/api/single', formData, { headers }).pipe(
        map(() => {
            return true;
        }),
        catchError((err) => throwError(handleError(err)))
    );
}

也可以用{ headers: new HttpHeaders().set('Content-Type', null) }替代,效果一致,都是让Angular不设置默认Content-Type,由浏览器根据FormData自动生成包含boundary的正确请求头。

内容的提问来源于stack exchange,提问作者user68288

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:15:47