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

Angular上传带图片的商品至NestJS时出现JSON解析语法错误求助

解决Angular上传商品到NestJS时的JSON解析错误

错误信息:SyntaxError: Unexpected token . in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad

在使用Angular将带图片的商品上传至NestJS服务器时出现上述错误,已确认商品及图片路径成功上传,但错误仍存在,无法定位问题出在前端还是后端。

Angular端代码(图片选择及上传相关逻辑)

async addfile() {
  let formData = new FormData();
  formData.set(
    'file',
    this.AddbookForm.value.coverimage,
    this.AddbookForm.value.coverimage.name
  );
  this.http
    .post('http://localhost:3000/images/upload', formData)
    .subscribe((res) => {});
}
async addbooks() {
  (await this.apiService.addbooks(this.AddbookForm.value)).subscribe(
    (res) => {
      console.log(res);
    }
  );
}

async uploadimage(event: any) {
  this.AddbookForm.value.coverimage = event.target.files[0];
  console.log('file', this.AddbookForm.value.coverimage);
}

问题根源

这个错误是前端尝试解析后端返回的非JSON格式内容导致的。Angular的HttpClient默认会期望接口返回JSON数据,如果后端返回的是纯字符串(比如直接返回图片路径./uploads/xxx.jpg),前端会强行调用JSON.parse解析,自然触发语法错误。

排查与解决

后端(NestJS)调整

检查/images/upload接口的返回逻辑:

  • 不要直接返回字符串,把结果包装成JSON对象,比如:
    // NestJS接口示例
    @Post('upload')
    async uploadFile(@UploadedFile() file: Express.Multer.File) {
      // 处理文件上传逻辑
      return { path: `./uploads/${file.filename}` }; // 返回JSON对象
    }
    
  • 确保接口响应头的Content-Type为application/json(NestJS默认返回JSON时会自动设置,无需手动处理)。

前端(Angular)调整

如果后端确实需要返回非JSON格式的内容(比如纯文本路径),在请求时显式指定responseType: 'text',关闭自动JSON解析:

this.http
  .post('http://localhost:3000/images/upload', formData, { responseType: 'text' })
  .subscribe((res) => {
    console.log('图片路径:', res);
    // 这里可以直接使用返回的字符串
  });

同时检查apiService.addbooks方法内部的请求配置,确保同样处理了响应格式,避免出现类似错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:24:56