从服务器授权用户登录我的应用程序。它是这样的:
用户将登录名和密码写入单独的输入中
当他单击“登录”按钮时,正在发送地址为http的请求:http://localhost/api/auth/${this.username}/${this.password}
服务器的响应是布尔值。如果登录名和密码正确,则响应为true,否则为false。
这是我的要求:
this.http.post(`http://localhost/api/auth/${this.username}/${this.password}`, cred, {
headers: headers
})
.map(res => res.json())
.subscribe(
data => this.response = data,
err => console.log('error'),
() => console.log('Authentication Complete')
);
我的问题是我不知道链接后面的那个
cred
变量是什么。我需要这些headers
吗?它甚至应该工作吗?我会回答所有答案。先感谢您。
编辑正确的登录名和密码为admin / admin。
因此,如果用户写admin / admin,它将返回
true
。 最佳答案
我建议您看一下TOH-Http,这是一个很好的教程!
是的,因为您只请求一个URL,所以不需要使用post。发布是针对您在发送请求时发送正文的信息。
正如我们在评论中讨论的那样,这是一个可行的解决方案:
this.http.get('http://localhost/api/auth/${this.username}/${this.password}')
.map(res => res.json())
.subscribe(d => console.log(d))
但我建议您在服务中进行映射(我想您正在服务中执行此请求),并在调用此http请求的组件中执行
.subscribe
。在您的情况下,由于您只收到false
或true
,因此可以这样操作: return this.http.get('http://localhost/api/auth/${this.username}/${this.password}')
.map((res: Response) => {
let resp = res.json();
if (resp == true) {
return true;
}
return false;
});
.catch(...
}
在您的方法中,您像这样调用http-request
.subscribe
:.subscribe(res => {
if(res == true) {
// do something...
} else {
// do something else...
}
})
如前所述,将来不要在url中发送用户名和密码! ;)