req.body在转发到另一个函数时被取消定义

时间:2018-03-21 18:38:55

标签: javascript node.js angular express

代码看起来像这样

saleComponent.html

<form class="form-horizontal" #salesdetails="ngForm" (ngSubmit)="onSubmit(salesdetails.value)">
        <div class="form-group" *ngFor="let label of labels">
            <label for="item1" class="col-sm-3 control-label">{{label}}</label>
            <div class="col-sm-9">
                <input type="text" value="" name="{{label}}" id="item1" ngModel>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-10">
                <button type="submit" class="btn btn-default">Add</button>
            </div>
        </div>
</form>

SaleComponent.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { SalesService } from '../sales.service';
import { Sale } from '../model/sale';

@Component({
  selector: 'app-sales',
  templateUrl: 'frontend/js/sales/sales.component.html',
  styleUrls: ['frontend/js/sales/sales.component.css']
})
export class SalesComponent implements OnInit {
    form;
    labels;
    sales : Sale[];

    constructor(private salesService: SalesService){}

    ngOnInit(){
        this.getLabels();
    }

    getLabels(){
        this.salesService.getLables().subscribe(labels => {
            this.labels = labels[0].attributes;
            console.log(labels);
        });

    }

    getSales(){

    }


    onSubmit(formValues){
        this.salesService.addSale(formValues).subscribe(response => {
            console.log(response);
        });
    }
}

SaleService.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Sale } from './model/sale';

@Injectable()
export class SalesService {
  private lablesUrl = "/sale/labels";
  private saleUrl = "/sale";

  constructor(private http: HttpClient) {
  }

  getLables(){
    return this.http.get(this.lablesUrl);
  }

  addSale(formValues){
    return this.http.post(this.saleUrl, formValues);
  }

  getSales(): Observable<Sale[]> {
    let sales = this.http.get<Sale[]>(this.saleUrl/*, this.authservice.options*/);
    console.log(sales)
    return sales;
  }

  deleteItems(idArray){
    return this.http.delete(this.saleUrl,idArray/*, this.authservice.options*/);
  }

}

routefile.js

route.post(&#39; / sale&#39;,saleDao.postSale);

saleDao.js

在saleDao.js中有一个名为postSale的函数,其中有一个函数名称为modifyLabels(),就像这样。

function postSale(req,res){
    console.log(req.body);//output the body of the request
    utility.modifyLabels(req);
}

utility.js

function modifyLabels(req){
   console.log(req.body); //outputs undefined;
}

我不知道为什么req.body显示这种行为

1 个答案:

答案 0 :(得分:0)

我有类似的问题。数据因某种原因被清除,并没有得到任何结果。为了解决这个问题,我使用了stat(2)对象,如下所示:

JSON

我希望这对你也有帮助。