我正在使用Ionic2,我想使用POST请求将数据从表单发送到Web服务,但是每次打印表单数据时,我发现它是空的,并且服务向我发送它没有收到数据。 这是我的 HTML 代码:
<div class="login-box">
<form #registerForm="ngForm">
<ion-row>
<ion-col id="imageContainer">
<button (click)="upload()" ion-button>Take Pic & Upload </button>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-list inset>
<ion-item>
<ion-label floating>{{ 'USERNAME' | translate }}</ion-label>
<ion-input type="text" name="username" #username required></ion-input>
</ion-item>
<ion-item>
<ion-label floating>{{ 'MOBILENUMBER' | translate }}</ion-label>
<ion-input type="text" name="mobile" #mobile required></ion-input>
</ion-item>
<ion-item>
<ion-label floating>{{ 'EMAILADDRESS' | translate }}</ion-label>
<ion-input type="email" name="email" #email required></ion-input>
</ion-item>
<ion-item>
<ion-label floating>{{ 'PASSWORD' | translate }}</ion-label>
<ion-input type="password" name="password" #password required></ion-input>
</ion-item>
<ion-item>
<ion-label floating>{{ 'CONFIRMPASSWORD' | translate }}</ion-label>
<ion-input type="password" name="confirmpass" #confirmPass required></ion-input>
</ion-item>
</ion-list>
</ion-col>
</ion-row>
<ion-row>
<ion-col class="signup-col">
<button ion-button class="submit-btn" (click)="signUp(username.value,email.value,password.value,mobile.value,confirmPass.value)" full type="submit" [disabled]="!registerForm.form.valid">sign up</button>
<button ion-button class="register-btn" block clear (click)="login()">sign in</button>
</ion-col>
</ion-row>
</form>
</div>
服务方式:
register(username,email,password,mobile,) {
let body = new FormData();
body.append('user_name',username);
body.append('email',email);
body.append('mobile',mobile);
body.append('password',password);
body.append('image','dsdsdsddsd');
console.log('body from service: ',body);
let headers = new Headers();
headers.append("Content-Type","application/formdata");
return this.http.post(this.registerUrl,body,{headers:headers})
.map((response:Response)=>response.json())
}
JS:
signUp(username,email,password,mobile,confirmPass) {
this.userService.register(username,email,password,mobile)
.subscribe(data=>{
console.log('register data from service: ',data);
},
(err)=> console.log('error: ',err)
)
}
这是从服务接收的数据: 对象 {结果: 数组(0(, 状态: 对象} 结果 : 阵列(0( 地位 : 对象 消息 : 阵列(4( 0 : "用户名字段为必填字段。" 1 : "电子邮件字段为必填项。" 2 : "移动领域是必需的。" 3 : "密码字段为必填项。" 长度 : 四
在发送请求之前,您必须字符串化数据,像这样使用此函数
let body = JSON.stringify(body) return this.http.post(this.registerUrl,body,{headers:headers})
.map((response:Response)=>response.json())