快递接收空对象 [英] Express receiving empty object

查看:95
本文介绍了快递接收空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Angular 2连接到Express。我已经使用Postman设置和测试服务器端点(内容类型似乎是x-www-form-encoded以使其工作)但除此之外我不知道是否有任何特殊配置的角度2来承载该请求。我的猜测是内容类型不正确或其他。

I am trying to connect Angular 2 to Express. I have already setup and test the server endpoint using Postman (content type seems to be x-www-form-encoded for it to work) but other than that i do not know if there is any special config for angular 2 to carry that request. My guess its that the content-type is not correct or something.

form.ts

import {Component, ViewEncapsulation} from "angular2/core";
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, AbstractControl, Validators, Control} from "angular2/common";
import { Http } from "angular2/http";

@Component({
    selector: "parameters-form",
    directives: [FORM_DIRECTIVES],
    templateUrl: "dev/form.template.html"
})
export class ParametersForm {
  myForm: ControlGroup;

  systemParameters: AbstractControl;
  param: AbstractControl;
  liftOperator: AbstractControl;
  restrictOperator: AbstractControl;
  xInitial: AbstractControl;

  system_arr: number[];
  param_arr: number[];
  restrict_arr: number[];
  lift_arr: number[];
  xinitial_arr: number[];

  constructor(fb: FormBuilder, private _http: Http) {
    this.myForm = fb.group({
      "realisations" : ["", Validators.required],
      "numConstSteps" : ["", Validators.required],
      "timeHorizon": ["", Validators.required],
      "continuationStep" : ["", Validators.required],
      "continuationStepSign" : ["", Validators.required],
      "numberOfModelParameters" : ["", Validators.required],
      "systemParameters" : [""],
      "param" : [""],
      "netLogoFile" : ["", Validators.required],
      "numberOfModelVariables" : ["", Validators.required],
      "restrictOperator" : [""],
      "liftOperator" : [""],
      "xInitial" : [""]

    });
    this.system_arr = [];
    this.param_arr = [];
    this.restrict_arr = [];
    this.lift_arr = [];
    this.xinitial_arr = [];
    this.param = this.myForm.controls["param"];
    this.systemParameters = this.myForm.controls["systemParameters"];
    this.restrictOperator = this.myForm.controls["restrictOperator"];
    this.liftOperator = this.myForm.controls["liftOperator"];
    this.xInitial = this.myForm.controls["xInitial"];
  }

  addToArray(event, value: number, target: string): void {
    if (event.which === 13) {

      switch (target) {
        case "systemParameters":
          this.system_arr.push(value);
          (<Control>this.systemParameters).updateValue("");
          break;
        case "param":
          this.param_arr.push(value);
          (<Control>this.param).updateValue("");
          break;
        case "liftOperator":
          this.lift_arr.push(value);
          (<Control>this.liftOperator).updateValue("");
          break;
        case "restrictOperator":
          this.restrict_arr.push(value);
          (<Control>this.restrictOperator).updateValue("");
          break;
        case "xInitial":
          this.xinitial_arr.push(value);
          (<Control>this.xInitial).updateValue("");
          break;

      }
    }
  }

  deleteItem(value: any, target: string): void {
    let pos = 0;
    switch (target) {
      case "systemParameters":
        pos = this.system_arr.indexOf(value);
        this.system_arr.splice(pos, 1);
        break;
      case "param":
        pos = this.param_arr.indexOf(value);
        this.param_arr.splice(pos, 1);
        break;
      case "liftOperator":
        pos = this.lift_arr.indexOf(value);
        this.lift_arr.splice(pos, 1);
        break;
      case "restrictOperator":
        pos = this.restrict_arr.indexOf(value);
        this.restrict_arr.splice(pos, 1);
        break;
      case "xInitial":
        pos = this.xinitial_arr.indexOf(value);
        this.xinitial_arr.splice(pos, 1);
        break;

    }
  }

  isFullfilled(m: number, n: number) {

    if (
          m == this.restrict_arr.length
          && m == this.xinitial_arr.length
          && m == this.lift_arr.length
          && n == this.param_arr.length
          && n == this.system_arr.length
       ) {
         if (m != 0 && n != 0 ){
           return true;
         }

       }

       return null;
  }
  onSubmit(form: any): void {
    let form = form;
    form.systemParameters = this.system_arr;
    form.liftOperator = this.lift_arr;
    form.restrictOperator = this.restrict_arr;
    form.param = this.param_arr;
    form.xInitial = this.xinitial_arr;

    this._http.post("http://localhost:3001/export", form).subscribe();
    console.log("your submitted value:", form);
  }

}

server.js

server.js

var express = require('express');
var bodyParser = require('body-parser')
var cors = require('cors');

var app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.post('/export', function(req, res){
  var body = req.body;
  res.send(body);
  console.log(body);
});

app.listen("3001", function(){
  console.log("Express server running on localhost:3001");
});


推荐答案

您需要明确设置 Content-Type 标题。 Angular2目前不会为你设置

You need to set explicitly the Content-Type header. Angular2 won't set it under the hood for you at the moment.

var headers = new Headers();
headers.append('Content-Type', 'x-www-form-encoded');
this._http.post("http://localhost:3001/export", form, {
  headers: headers
}).subscribe();

此外,您需要利用 URLSearchParams 类构建主体并将其转换为字符串。目前,身体只能作为字符串提供给帖子 / put / 补丁 Http 类的方法。

Moreover you need to leverage the URLSearchParams class to build the body and convert it as a string. At the moment, the body can only be provided as a string to the post / put / patch method of the Http class.

var form = new URLSearchParams();
form.set('systemParameters', this.system_arr);
form.set('liftOperator', this.lift_arr);
(...)

this._http.post("http://localhost:3001/export", form.toString(), {
  headers: headers
}).subscribe();

不要忘记导入标题 class:

Don't forget to import the Headers class:

import {Http, Headers} from 'angular2/http';

这篇关于快递接收空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆