我想在nodeJs服务器端处理POST请求,而不使用像ExpressJS这样的框架。post请求在客户端运行良好,但无法获取POST请求中包含的文件或字段。下面是使用的客户端和服务器端代码。
Angular 7.1.4中的客户端代码
filelist: FileList 
file: File
sendFile(){
console.log("Send called")
let formdata: FormData = new FormData();
formdata.append('uploadedFile',this.file,this.file.name)
formdata.append('test',"test")
console.log(formdata)
let options = {
  headers:new HttpHeaders({
    'Accept':'application/json',
    'Content-Type':'multipart/form-data'
  })
}
this._http.post('http://localhost:3000/saveFile',formdata,options)
          .pipe(map((res:Response) => res),
                catchError(err => err)
                ).subscribe(data => {
                  console.log("Data is " + data)
                })
}我的HTML代码
<mat-accordion>
<mat-expansion-panel [expanded]='true' [disabled]='true'>
<mat-expansion-panel-header>
  <mat-panel-title>
    Upload File
  </mat-panel-title>
</mat-expansion-panel-header>
<mat-form-field>
  <input matInput placeholder="Work Id">
</mat-form-field>
  <input type="file" (change)="fileChange($event)" >
  <button mat-raised-button color="primary" 
  (click)="sendFile()">Upload</button>
  </mat-expansion-panel>
  </mat-accordion>NodeJS v10.13.0中的服务器端代码
//Get the payload
let decoder = new StringDecoder('utf-8')
let buffer = ''
//Listen to request object on data event
req.on('data',(reqData) => {
    console.log("Request Data " + reqData)
    //perform action on the request object
    buffer += decoder.write(reqData)
})
//Listen to request object on end event
req.on('end',() => {
    buffer += decoder.end();
    let form = new formidable.IncomingForm();
    form.parse(req,(err,fields,files) => {
        console.log(fields)
    })我使用的是formidable,但没有获得附加到formData对象中的字段或文件。下面是我得到的输出
Request Data ------WebKitFormBoundary2SOlG50JexpNBclX
Content-Disposition: form-data; name="uploadedFile"; filename="test.txt"
Content-Type: text/plain
//File content
test;test;test;test;test;test;test;test;test;test;test;test
test;test;test;test;test;test;test;test;test;test;test;test
------WebKitFormBoundary2SOlG50JexpNBclX
Content-Disposition: form-data; name="test"
test
------WebKitFormBoundary2SOlG50JexpNBclX--发布于 2019-02-28 19:10:37
'Content-Type':'multipart/form-data'
多部分/表单数据MIME类型需要boundary属性。
通常,XMLHttpRequest会从FormData对象自动生成它,但是在默认情况下,Angular会覆盖Content-Type,然后您会再次覆盖它。
因此,Formidable不知道边界在哪里,也无法处理请求。
你需要阻止Angular覆盖它:
  headers:new HttpHeaders({
    'Accept':'application/json',
    'Content-Type': null
  })https://stackoverflow.com/questions/54924224
复制相似问题