【问题标题】:Send File from Angular to Nodejs - Cannot read property 'headers' of undefined将文件从 Angular 发送到 Nodejs - 无法读取未定义的属性“标题”
【发布时间】:2020-08-15 04:50:15
【问题描述】:

我在将带有文件的数据传递到我的 nodejs 后端时遇到问题。我目前正在使用 azure 函数来运行我的 nodejs 代码。目前,当我通过文件传递数据时,我得到一个Cannot read property 'headers' of undefined 我在选项中添加了标题所以我真的不明白为什么会出现错误。使用文件绝对是我的一个弱点,所以我很感激任何帮助!

import { Injectable, OnDestroy } from "@angular/core";
import { Subject, Observable } from "rxjs";
import {
  HttpClient,
  HttpParams,
  HttpRequest,
  HttpHeaders,
  HttpEvent,
  HttpEventType
} from "@angular/common/http";
import { map, takeUntil, switchMap } from "rxjs/operators";
import { Router } from "@angular/router";
import { environment } from 'src/environments/environment';
import { AuthService } from '../auth.service';
import { SendAppealModel } from './send-appeal.model';

@Injectable({ providedIn: "root" })
export class SubmitAppealService implements OnDestroy {

  destroy = new Subject();

  constructor(private http: HttpClient, private router: Router, private authService: AuthService) { }

  ngOnDestroy() {
    this.destroy.next();
    this.destroy.complete();
  }

  submitAppeal(
    username: string,
    email: string,
    file: File
  ) {


    let form = new FormData();
    form.append('file', file);
    form.append('username', username);
    form.append('email', email);

    console.log("FILE OUTPUT");
    console.log(file);

    let headers = new HttpHeaders();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    let options = { headers: headers, reportProgress: true };

    const api = environment.azure_function_url + `/PATCH-Send-Appeal`;
    const req = new HttpRequest('PATCH', api, form, options);

    return this.http.request(req)
      .pipe(
        map((res: HttpEvent<any>) => {
          if (res.type === HttpEventType.Response) {
            return res.body.id.toString();
          } else if (res.type === HttpEventType.UploadProgress) {
            // Compute and show the % done:
            const UploadProgress = +Math.round((100 * res.loaded) / res.total);
            return UploadProgress;
          }
        })
      );

  }

}

天蓝色函数


const multer = require('multer');
const upload = multer({ dest: 'public/uploads/' }).single('file');

module.exports = function (context, req) {
  context.log('JavaScript HTTP trigger function processed a request.');
  upload();


  console.log(req.file);
  var filename = path.basename("../" + req.file.path);
  console.log("filename");
  console.log(req.file.destination);
  console.log(__dirname);

  var form = new formidable.IncomingForm();

  console.log("form");
  console.log(form);


  context.res = {
    status: 200,

    headers: {
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'PATCH, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Set-Cookie',
      'Access-Control-Max-Age': '86400',
      Vary: 'Accept-Encoding, Origin',
      'Content-Type': 'application/json',
    },
  };


  context.done();
};

【问题讨论】:

    标签: node.js angular http azure-functions


    【解决方案1】:

    我假设您收到该错误是因为您的 headers 并没有真正实现您的 azure 功能。

    目前你有这个:

    let headers = new HttpHeaders();
    headers.append('Content-Type', 'multipart/form-data');
    headers.append('Accept', 'application/json');
    let options = { headers: headers, reportProgress: true };
    

    你不能那样做。 headers.append 不进行就地更新。它返回一个新的HttpHeaders 对象。所以,你实际上需要这个:

    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'multipart/form-data');
    headers = headers.append('Accept', 'application/json');
    let options = { headers: headers, reportProgress: true };
    

    每个 cmets,我看到另一件事对我来说有点不对劲。这可能是问题的一部分。尝试将您的 HTTP 调用更新为:

    const req = new HttpRequest('PATCH', api, form, options);

    return this.http.patch(api, form, options)
      .pipe(
        map((res: HttpEvent<any>) => {
          if (res.type === HttpEventType.Response) {
            return res.body.id.toString();
          } else if (res.type === HttpEventType.UploadProgress) {
            // Compute and show the % done:
            const UploadProgress = +Math.round((100 * res.loaded) / res.total);
            return UploadProgress;
          }
        })
      );
    

    您还可以在第一行的 azure 函数中设置断点,以检查请求对象并确保您的 HttpHeaders 正在进入。

    【讨论】:

    • 我更改了代码以反映您的答案,但我仍然遇到同样的错误。更新代码:pastebin.com/5EKT2BrU
    • 澄清一下,您在节点代码中遇到了上述错误,而不是角度错误。正确的?如果是这样,请粘贴完整的 stracktrace。
    • 纠正这是一个后端错误。给你:pastebin.com/jQpJ0abs
    • 嗯....奇怪。我看到另一件事看起来很奇怪。更新了我的问题。
    • 我也对upload() 函数的作用感兴趣。了解您可以调试节点函数的程度也很有帮助(即:抛出异常的行是哪一行)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2020-12-19
    • 2022-12-07
    • 2015-04-06
    相关资源
    最近更新 更多