Nodejs returns undefined for Angular 2 request

2019-09-07 01:09发布

问题:

I want to post the data from my Ionic 2 application with http.post method to server, but the server returns undefined.

I had tried to send a string once, but the result is the same.

Here is the Angular 2 client side code:

  import { Component } from '@angular/core';
  import { NavController, NavParams } from 'ionic-angular';
  import { RegisterPage } from '../register/register';
  import { Http, Headers } from '@angular/http';
  import { ToastController } from 'ionic-angular';
  import { User } from '../../providers/user';

  @Component({
    selector: 'page-login',
    templateUrl: 'login.html'
  })
  export class LoginPage {

  private accounts: Object[] = []
  private headers: Headers;

  private http;

  private toast;

  public email;
  public password;

  public user: User;

  constructor(public navCtrl: NavController, public navParams: NavParams, 
    http: Http, public toastCtrl: ToastController) {

   this.http = http;
   this.toast = toastCtrl;
  }

  ngAfterViewInit() {

  }

  toastMessenger(res : string) {
    let toast = this.toast.create({
      message: res,
      duration: 3000
    });

    toast.present();
  }

  submit() {
    let headers = new Headers();
    headers.append("Content-Type", 'application/json');

    console.log(this.email)

    this.http.post('http://localhost:3000/validation', JSON.stringify(this.email), { headers: headers })
    .subscribe(() => {
      console.log("Dados enviados com sucesso");
    });
}

  changeToRegister() {
   this.navCtrl.push(RegisterPage);
  }
}

And this is my post verb route:

  app.post('/validation', function(req, res) {
     console.log(req.body); // => undefined
  });

回答1:

I finally got the error. I was importing the routes before setting up the body parser.

  // config/express.js
  consign()
   .include('infra')
   .then('app/routes')
   .into(app);

   app.use(bodyParser.json());                                                                                                                
   app.use(bodyParser.urlencoded({extended: true}));  

When a set fix this, the server returns the json object that i want

  // config/express.js
   app.use(bodyParser.json());                                                                                                                
   app.use(bodyParser.urlencoded({extended: true}));  

   consign()
     include('infra')
     .then('app/routes')
     .into(app);

Thank you all for trying to help.