本文介绍了Nodejs为Angular 2请求返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将带有http.post方法的Ionic 2应用程序的数据发布到服务器,但是服务器返回undefined。

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.

这是Angular 2客户端代码:

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);
  }
}

这是我的动词后路线:

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


推荐答案

我终于得到了错误。我在设置正文解析器之前导入了路径。

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}));

当一个集合修复此问题时,服务器返回我想要的json对象

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);

谢谢大家的帮助。

这篇关于Nodejs为Angular 2请求返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:52