首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >处理带有formdata的post请求,节点中没有express

处理带有formdata的post请求,节点中没有express
EN

Stack Overflow用户
提问于 2019-02-28 19:05:02
回答 1查看 571关注 0票数 0

我想在nodeJs服务器端处理POST请求,而不使用像ExpressJS这样的框架。post请求在客户端运行良好,但无法获取POST请求中包含的文件或字段。下面是使用的客户端和服务器端代码。

Angular 7.1.4中的客户端代码

代码语言:javascript
运行
复制
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代码

代码语言:javascript
运行
复制
<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中的服务器端代码

代码语言:javascript
运行
复制
//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对象中的字段或文件。下面是我得到的输出

代码语言:javascript
运行
复制
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--
EN

回答 1

Stack Overflow用户

发布于 2019-02-28 19:10:37

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

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

通常,XMLHttpRequest会从FormData对象自动生成它,但是在默认情况下,Angular会覆盖Content-Type,然后您会再次覆盖它。

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

你需要阻止Angular覆盖它:

代码语言:javascript
运行
复制
  headers:new HttpHeaders({
    'Accept':'application/json',
    'Content-Type': null
  })
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54924224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档