标头和正文数据在http请求中变为空

时间:2018-02-23 12:33:39

标签: node.js http express form-data angular4-forms

这就是我的服务book.service.ts的外观

import {Injectable} from '@angular/core';
import {Http,Response,Headers,RequestOptions} from '@angular/http';
import {NgForm} from '@angular/forms';
import {Books} from './books'
import {Observable} from 'rxjs/Observable'
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class BooksService
{
  private api = "api";
  constructor(private http:Http){}
   add_book(add_book_form,book_pdf_copy:FileList,book_pdf_sample:FileList,book_cover_image:FileList):Observable<Books[]>
  {

    let formData:FormData = new FormData();
    let pdf_copy: File = book_pdf_copy[0];
    let pdf_sample: File = book_pdf_sample[0];
    let cover_image: File = book_cover_image[0];
    for(let b in add_book_form)
    formData.append(b, add_book_form[b]);
    //console.log(formData);    
    formData.append('book_pdf_copy', pdf_copy, pdf_copy.name);
    formData.append('book_pdf_sample', pdf_sample, pdf_sample.name);
    formData.append('book_cover_image', cover_image, cover_image.name);
    let headers = new Headers(      );

    let options = new RequestOptions({headers:headers});
    return this.http.post(this.api+'/add_book',formData,options)
    .map(this.extractPromiseData)
    //.toPromise()
    .catch(this.handleError);
}

extractPromiseData(res:Response)
{
    let body = res.json();
    return body;
}

// handleError(error:Response)
// {
//     throw(error);
// }

private handleError (error: Response | any) {
    //console.error(error.message || error);
    return Observable.throw(error.message || error);
    }
 }

但是当我在表单提交上执行上述函数时,firefox开发人员控制台没有显示此请求的标题

我在互联网上搜索相关文章,但我没有找到任何解决方案。我正在使用和angular 4和nodejs表达框架。当我尝试在nodejs中记录req.body时,它显示空体。请帮我解决这个问题。我最近更新到angular2,同样的FormData在升级到angular 4之前工作正常。我知道它与Formdata和标题选项有关,但不知道如何解决它。任何帮助都会有所帮助。

谢谢,

2 个答案:

答案 0 :(得分:0)

好吧,你的标题可能是空的,因为至少在代码示例中,它们是空的。

试试这个:

const data = new FormData();
// ... rest
const headers = new Headers({
  'Content-Type': "multipart/form-data"
});
const options = new RequestOptions({ headers });
return this.http.post(url, data, options)
  .map(res => res.json());

答案 1 :(得分:0)

我刚刚在nodejs后端api的开头添加了return语句,只需从代码中删除return语句,在firefox开发者控制台中可以看到标题,从而添加以下代码

const fileUpload = require('express-fileupload');
app.use(fileUpload());
server.js中的

解决了问题。

由于