使用 API 的 Ionic 3 登录身份验证 - 无法读取 null 的属性“json" [英] Ionic 3 Login Authentication Using API - Cannot read property 'json' of null
问题描述
我正在使用 API 在 Ionic 3 中进行身份验证,但在登录过程中,它显示错误:Cannot read property 'json' of null
这是我的提供者>restapi>restapi.ts
import { HttpClient } from '@angular/common/http';从@angular/core"导入{可注射};从@angular/http"导入 {Http, Headers};让 apiUrl = 'http://192.168.1.10/honeybee/HoneyApi/';@Injectable()导出类 RestapiProvider {构造函数(公共 http:HttpClient){console.log('Hello RestapiProvider Provider');}getUsers(凭据,类型){返回新的承诺((解决,拒绝)=> {var headers = new headers();headers.append('Access-Control-Allow-Origin', '*');headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');headers.append('Accept','application/json');headers.append('content-type','application/json');this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers}).subscribe(res => {解决(res.json());}, (错误) =>{拒绝(错误);});});}}
这是我的登录页面.ts
import { Component } from '@angular/core';import { IonicPage, NavController, NavParams } from 'ionic-angular';从'../../providers/restapi/restapi'导入{RestapiProvider};从 '../list/list' 导入 { ListPage };@IonicPage()@成分({选择器:'页面登录页面',templateUrl: 'loginpage.html',})导出类 LoginpagePage {响应数据:任何;userData = {"email": "", "password": ""};构造函数(公共导航控件:导航控制器,公共导航参数:导航参数,公共restProvider:RestapiProvider){}ionViewDidLoad() {console.log('ionViewDidLoad LoginpagePage');}获取登录用户(){this.restProvider.getUsers(this.userData,'user_Login').then((result) => {this.responseData = 结果;如果(this.responseData.userData){控制台日志(this.responseData);console.log("用户详细信息");this.navCtrl.push(ListPage);}别的{console.log("不正确的细节");}}, (错误) =>{//错误日志});}}
这是我的 loginpage.html
<离子导航栏><ion-title>登录页面</ion-title></ion-navbar></ion-header><离子含量填充><form (submit)="getloginUsers()"><离子列表><离子项目><ion-label fixed>Email</ion-label><ion-input type="email" [(ngModel)]="userData.email" name="email"></ion-input></ion-item><离子项目><离子标签固定>密码</离子标签><ion-input type="password" [(ngModel)]="userData.password" name="password"></ion-input></ion-item><div 填充><button ion-button color="primary" block>登录</button>
</ion-list></表单></离子含量>
当我点击登录按钮时,我得到了一个无法读取的 null 属性 'json'.任何帮助提前表示赞赏.请帮忙.
第一:
如果您在配置文件中添加FormsModule
,ngModel 可以工作.
@NgModule({声明:[ MyApp ],进口:[表单模块...)],引导程序:[...],entryComponents: [ ... ],提供者:[]})
第二:
以JSON格式发送数据,添加Content-Type:
getUsers(credentials, type) {让标题=新标题();headers.append('Content-Type', 'application/json');返回 this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers}).map(res => res.json());}
并调用loginpage
(无承诺)
this.restProvider.getUsers(this.userData,'user_Login').subscribe(res => this.responseData = 结果);
第三:
后端必须返回成功值.如果您的 API 有错误(没有有效的电子邮件、密码),则向客户端返回 HTTP 错误.
<小时>CORS 标头必须在服务器上实现部分.
I am doing authentication in Ionic 3 using API but In the login process, it is showing error: Cannot read property 'json' of null
This is my providers>restapi>restapi.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
let apiUrl = 'http://192.168.1.10/honeybee/HoneyApi/';
@Injectable()
export class RestapiProvider {
constructor(public http: HttpClient) {
console.log('Hello RestapiProvider Provider');
}
getUsers(credentials, type) {
return new Promise((resolve, reject) => {
var headers = new Headers();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('content-type','application/json');
this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
}
This is my loginpage.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RestapiProvider } from '../../providers/restapi/restapi';
import { ListPage } from '../list/list';
@IonicPage()
@Component({
selector: 'page-loginpage',
templateUrl: 'loginpage.html',
})
export class LoginpagePage {
responseData : any;
userData = {"email": "", "password": ""};
constructor(public navCtrl: NavController, public navParams: NavParams,
public restProvider: RestapiProvider) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginpagePage');
}
getloginUsers(){
this.restProvider.getUsers(this.userData,'user_Login').then((result) => {
this.responseData = result;
if(this.responseData.userData){
console.log(this.responseData);
console.log("User Details");
this.navCtrl.push(ListPage);
}
else{
console.log("Incorrect Details"); }
}, (err) => {
// Error log
});
}
}
This is my loginpage.html
<ion-header>
<ion-navbar>
<ion-title>loginpage</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form (submit)="getloginUsers()">
<ion-list>
<ion-item>
<ion-label fixed>Email</ion-label>
<ion-input type="email" [(ngModel)]="userData.email" name="email"></ion-input>
</ion-item>
<ion-item>
<ion-label fixed>Password</ion-label>
<ion-input type="password" [(ngModel)]="userData.password" name="password"></ion-input>
</ion-item>
<div padding>
<button ion-button color="primary" block>Login</button>
</div>
</ion-list>
</form>
</ion-content>
I am getting a Cannot read property 'json' of null when I click the login button. Any help appreciated in Advance. Please Help.
First:
ngModel work if you addition FormsModule
in config file.
@NgModule({
declarations: [ MyApp ],
imports: [
FormsModule
...
)],
bootstrap: [...],
entryComponents: [ ... ],
providers: []
})
Second:
Send data as JSON format, add Content-Type:
getUsers(credentials, type) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
.map(res => res.json());
}
and call in loginpage
(without Promise)
this.restProvider.getUsers(this.userData,'user_Login')
.subscribe(res => this.responseData = result);
Third:
Back-end must return success value. If your API has error (no valid email, password) return HTTP error to Client.
CORS headers must be implementation on the Server Part.
这篇关于使用 API 的 Ionic 3 登录身份验证 - 无法读取 null 的属性“json"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!