带有Angular 5和Express JS的JSON中位置0处的意外令牌#

时间:2018-06-22 17:18:42

标签: angular5

我正在开发MEAN堆栈应用程序

where My client is in Angular 5 and backend is in node and express js with mongo db as my storage.

I am trying to upload an image from one my Angular Page to my express js rest API which will finally upload the image in AWS cloud

Sample code for my Component is as below having two methods one onFileSelected which sets the selected file and the onUpload which invokes a service class method


private selectedFile:File=null;


onUpload(){
    this.productCategoryService.
    uploadProductCategoryImage(this.selectedFile).subscribe(
      data=>{console.log("Upload success---"+data)},
      err=>{console.log("Upload error ---"+err.message)});
}


onFileSelected(event){
    this.selectedFile=event.target.files[0];
    console.log("this.selectedFile---------"+this.selectedFile);
}

The service does a post call of rest service on express js.Code of my service class is as below


public uploadProductCategoryImage(selectedFile:File){
        const formData = new FormData();
        formData.append("userFile",selectedFile);
        return this.http.post<any>
        ('http://localhost:3000/datastore/api/aws/api/file',formData);       
}

My html page

<input type="file" (change)="onFileSelected($event)" name="userFile">
<button type="button" class="btn btn-success" (click)="onUpload()">
<span class="fa fa-upload"></span>Upload</button>

However when I post this data I get an error as below on the server side

SyntaxError: Unexpected token # in JSON at position 0
    at JSON.parse (<anonymous>)

我在浏览器中发现了一些东西,它显示了BAD请求。 我不确定发生了什么。请提出建议。

常规------------ 要求网址:http://localhost:3000/datastore/api/aws/api/file 请求方法:POST 状态码:400错误请求 远端地址:[:: 1]:3000 推荐人政策:降级时不推荐人

响应标题------------ 访问控制允许来源:* 连接:保持活动状态 内容长度:1314 内容安全策略:default-src'self' 内容类型:text / html;字符集= utf-8 日期:2018年6月22日,星期五,16:47:12 GMT X-Content-Type-Options:nosniff X-Powered-By:快递

请求标头-------------------- 接受:application / json 接受编码:gzip,deflate,br 接受语言:en-GB,en-US; q = 0.9,en; q = 0.8 连接:保持活动状态 内容长度:232378 内容类型:application / json 主机:localhost:3000 来源:http://localhost:4200 推荐人:http://localhost:4200/contactus 用户代理:Mozilla / 5.0(X11; Linux x86_64)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 67.0.3396.62 Safari / 537.36 ------ WebKitFormBoundaryAEgWhmyP5LdwDaEl 内容处置:表单数据; name =“ userFile”; filename =“屏幕截图来自2018-06-04 20-23-28.png” 内容类型:image / png

谢谢 萨钦(Sachin)

1 个答案:

答案 0 :(得分:1)

在Angular 5中,Httpclient使用JSON作为默认格式。因此,您已经使用 BLOB 作为响应类型,例如

  getImage(imageUrl: string): Observable<Blob> {
    return this.httpClient.get(imageUrl, { responseType: 'blob' });
  }

检查此链接以供参考:https://stackblitz.com/edit/angular-1yr75s?file=src%2Fapp%2Fimage.service.ts