我需要在我的Ionic 2应用程序中实现登录。现在,我只需确保电子邮件和密码得到正确接收并获得基本回复。Ionic 2 - 如何提出登录请求?
我已经成功地测试了一个GET请求到API,它正常工作,但我无法获得POST请求的工作。
我已经尝试了两种方法:
使用
subscribe
:登录组件:
submitLogin() { var email = this.loginForm.value.email.trim(); var password = this.loginForm.value.password.trim(); this.userService.makeLogin(email, password); }
服务:
makeLogin(email: string, password: string) { var body = JSON.stringify({ email: email, password: password }); var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); this.http .post(this.loginUrl, body, { headers: headers }) .subscribe(data => { console.log('login API success'); console.log(data); }, error => { console.log(JSON.stringify(error.json())); }); }
的API(笨):(代码最低为测试目的)
public function testLoginIonic2() { header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); $account_email = $this->input->post('email'); $account_password = $this->input->post('password'); echo json_encode($account_email); }
结果:
到服务器的连接,似乎好 - 但没有数据被返回 - 响应的主体为空
使用
Promise
:登录组件:
submitLogin() { var email = this.loginForm.value.email.trim(); var password = this.loginForm.value.password.trim(); this.userService.testLogin(email, password) .then(data => { console.log('response data'); console.log(data); }); }
服务:
testLogin(email: string, password: string): Promise<any> { var body = JSON.stringify({ email: email, password: password }); var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); return this.http .post(this.loginUrl, body, {headers: headers}) .toPromise() .then(res => res.json().data); }
API:同
前结果:
我收到此错误信息:
Unexpected end of JSON input
(可能是因为响应是空的,因此不能以JSON格式)。
为什么我会得到一个空的回应?
表单正常工作。错误不在那里。
所以请求中肯定有错,但是什么?
编辑:
测试与波兹曼看来,参数是空的。可能它们没有正确发送。
因为email是字符串类型,我认为它应该是'echo json_encode({“email”:$ account_email});'因为你期望数据是json格式。我不知道codeIgniter,所以只是一个建议:-) –
以邮递员为例,并尝试调用您的后端。如果它没有返回你期望的结果,那么pb来自你的后端,并且与前端或者angular2无关。 – Maxime
非常好的建议!这似乎确实没有正确发送参数。这就是为什么要清空响应。在Postman中,如果将参数设置为原始数据,则会发生相同的情况。如果我将它们作为x-www-form-urlencoded或表单数据输入,那么我会正确回复电子邮件作为回复。 – johnnyfittizio