【问题标题】:Angular 7.2.3, sent post data by "files". (In Express recolect that data by "req.files")Angular 7.2.3,通过“文件”发送帖子数据。 (在 Express 中通过“req.files”重新收集该数据)
【发布时间】:2019-04-24 00:25:28
【问题描述】:

My Express API REST 支持上传图片。

我使用 Postman 进行测试,我通过req.files 接收图像,现在在我的 Angular 项目中,图像默认由 req.body 发送。

我尝试设置标题'Content-type': 'multipart/form-data',设置观察到files(因为只接受'body'而出错),设置'Response-Type': 'blob' as 'json' 和更多罕见的东西。

我的快递功能是:

exports.newPhoto = function(req, res) {
   if(!req.files || !req.files.imageAvatar) { 
            return res.status(300).json({
                status: 'fail', data: 'The request must have imageAvatar file'
            }) 
        }
        imageAvatar = req.files.imageAvatar
        name = imageAvatar.md5 + path.extname(imageAvatar.name)
        ...
}

在 Angular 项目中:

uploadImage(event) {
    /*upload-avatar.component.ts*/
    this.api.uploadPhoto(event.target.files[0]).subscribe(
    res => {
       ...
    }, err => {
      console.err(err);
    });
  }
/*api.service.ts*/
uploadPhoto(file: File) {
    const formData = new FormData();
    formData.append('imageAvatar', file, file.name);
    return this.http.post('http://localhost:3000/api/usuarios/imagen', formData);
  }

我查了很多教程和这个页面的其他线程,代码总是一样的。
假设 Angular 应该将其视为multipart/form-data,但在请求标头中始终显示Content-Type: application/json

这里有一些图片来说明问题:

我的实际问题:

我预计:

【问题讨论】:

    标签: angular express multipartform-data angular7 angular-httpclient


    【解决方案1】:

    我的错误是默认设置 interceptor ??‍♂ 中的标头,因为在我的 API 中使用 JWT 并且对于几乎所有请求,我必须输入 'Content-type': 'application/json'

    @Injectable()
    export class JWTInterceptor implements HttpInterceptor {
      constructor(private authenticationService: AuthenticationService) {}
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
        const token = this.authenticationService.getToken();
        if (token) {
          req = req.clone({
            setHeaders: { Authorization: token }
          });
        }
    
        req = req.clone({
          setHeaders: {'Content-Type': 'application/json'}
        });
    
        return next.handle(req);
      }
    }
    

    我留下它以防有人发生同样的事情?
    我希望你有一个美好的一天和快乐的编码❤️

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-23
      • 2019-02-07
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 2015-07-07
      相关资源
      最近更新 更多