用户登录我的应用程序时由服务器授权。它的工作原理如下:
用户将登录名和密码写入单独的输入
当他单击登录按钮时,将向地址发送 http post 请求:
http://localhost/api/auth/${this.username}/${this.password}
服务器的响应是 bool 值。如果登录名和密码正确,则响应为 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
变量是什么。我需要这些 header
吗?它甚至应该起作用吗?
我会对每个答案都投赞成票。先感谢您。
编辑正确的登录名和密码是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 中发送您的用户名和密码! ;)
关于javascript - 使用POST方法给用户授权::Angular2&TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41399058/