我是棱角分明的新人。我正在为我的课程做一些实验课。实验室作业是使用角度2编写笔记应用程序。我一直在努力设置请求标题。用户需要登录才能创建备注。当用户登录到应用程序时,节点服务器发送令牌作为确认。我将令牌保存在localstorage中。这工作,我可以在组件模板中看到令牌和打印。帖子请求必须附加标题的授权,我确实附加了登录凭据。但是当我发送邮件请求时,我得到401 Unauthorized。在这里我的代码 //响应令牌在本地存储中保存如下
login(username: string, password: string) {
const body = JSON.stringify({username: username, password: password}); // Stringify payload
const headers = new Headers();
headers.append( 'Content-Type', 'application/json' ); // ... Set content type to JSON
const options = new RequestOptions({ headers: headers }); // Create a request option
return this._http.post(this.loginUser, body, options) // ...using post request
.map((res: Response) => {
const token = res.json() && res.json().token;
if (token) {
localStorage.setItem('currentUser', JSON.stringify(res.json().id_token));
console.log(res.json().token);
}
})
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
//设置请求头并发送帖子请求
createPost(title: string, text: string) {
const body = JSON.stringify({noteData: {title: title, text: text}}); // Stringify payload
const headers = new Headers();
const token = localStorage.getItem('currentUser');
headers.append( 'Content-Type', 'application/text' ); // ... Set content type to JSON
headers.append('Authorization' , `Bearer ${token}`);
const options = new RequestOptions({ headers: headers }); // Create a request option
return this._http.post(this.createNote, body, options) // ...using post request
.map((res: Response) => {
console.log(res);
})
.catch((error: any) => Observable.throw(
error.json().error || 'Server error'));
}