【发布时间】: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