【问题标题】:formdata is not reaching the backendformdata 没有到达后端
【发布时间】:2021-11-05 18:59:30
【问题描述】:

我在我的应用程序中提交一个 html 表单,在从 Angular 前端发送 http 请求之前在控制台中获取提交的数据,但数据没有到达 NodeJS 的后端。当我从邮递员提交表单时,代码正在运行。

 <form [formGroup] = "myform" (ngSubmit) = "myFormSubmit()">
 <input type="text" placeholder="Name" formControlName="name">
 <div *ngFor="let data of dataArr;index as i>
 <input type="checkbox" id="1" [value]="data.id" name="{{ data.id }}" 
 (change)="getSelectedData($event)" formArrayName="checkboxData">
 </div>
 <button type="submit" [disabled] = "!myform.valid">Save</button>
 </form>

 myFormSubmit() {
   console.log(this.myform.value); // i can see all submitted form values here
   this.service.postmyForm(this.myform.value).subscribe(response =>{
 });
 }

 private headerData = {
 headers: new HttpHeaders({
  'Content-Type': 'application/x-www-form-urlencoded',
  'Content-Length': '541385555',
  'Authorization': `Bearer ${this.token}`
})
};

public postmyForm(formData): Observable<any> {
  console.log('formData'+ JSON.stringify(formData)); //i can see submitted data in console
  return this.http.post(this.url+ '/adduser', { formData }, this.headerData);
}

Nodejs Backend:-  
 @Post('/adduser')
  adduser(@Request() req) {
    console.log(req.body.name);return;  //Am not getting the form value here
  }

【问题讨论】:

  • 当你使用 Postman 发送数据时它是否有效?另外,请检查req.body,当您使用 Angular 发送表单时,您的表单可能带有 formData 键。

标签: node.js angular nestjs


【解决方案1】:

试试

return this.http.post(this.url+ '/adduser', formData, this.headerData);

formData 周围没有{ }

原因是你通过{ }发送的正文将是

 { 
   "formData": {
              name: "something",
              ....
            }
          }

当您尝试在此处使用名称 console.log(req.body.name) 直接访问它时,您的版本应该是 console.log(req.body.formData.name)

但是,如果您删除 { },则可以使用 console.log(req.body.name) 访问它,因为该对象将以以下形式传递

 { 
    "name": "something",
    ...
  }

【讨论】:

  • 哦!十分感谢你的帮助!很遗憾我无法弄清楚我应该使用一些我认为的调试器!
  • 但我想知道在后端我什至无法控制台 req,req.body.formData, req.body.formData.name!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多