使用formdata处理发布请求而不在节点中表达

时间:2019-02-28 11:05:02

标签: javascript node.js formidable

我想在nodeJs服务器端处理POST请求,而不使用ExpressJS之类的框架。发布请求在客户端可以正常工作,但无法获取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--

1 个答案:

答案 0 :(得分:-1)

   'Content-Type':'multipart/form-data'

多部分/表单数据MIME类型需要boundary属性。

通常,XMLHttpRequest将自动从FormData对象生成此内容,但是Angular默认会覆盖Content-Type,然后您将再次覆盖它。

因此,Formidable不知道边界在哪里,也无法处理请求。

您需要阻止Angular覆盖它:

  headers:new HttpHeaders({
    'Accept':'application/json',
    'Content-Type': null
  })
相关问题