我想使用 POST 方法通过 Angular 注销,这是我的代码:
logout() {
const url = 'http://localhost:8181/user/logout';
const xToken = localStorage.getItem('xAuthToken');
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new Headers({
'x-auth-token': xToken,
'Authorization': basicHeader
});
// return this.http.get(url, { headers: headers }); // This will work
return this.http.post(url, { headers: headers }); // This will generate error
}
这是我的后端:
@RequestMapping("/user/logout")
public ResponseEntity<String> logout(){
SecurityContextHolder.clearContext();
return new ResponseEntity<String>("Logout Successfully!", HttpStatus.OK);
}
奇怪的是上面的代码可以使用this.http.get但会生成以下错误this.http.post。这是错误的this.http.post:
POST http://localhost:8181/user/logout 401
如果我使用 HttpClient 修改代码,如下所示:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class LoginService {
constructor(private http: HttpClient) {
}
sendCredential(username: string, password: string) {
let url = "http://localhost:8181/token";
let encodedCredentials = btoa(username + ":" + password);// encode in base64 to send a token
let basicHeader = "Basic " + encodedCredentials;
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': basicHeader
})
// send credential method when login component
return this.http.get(url, { headers: headers }); // Error at this line
}
checkSession() {
const url = 'http://localhost:8181/checkSession';
const xToken = localStorage.getItem('xAuthToken');
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new Headers({
'x-auth-token': xToken,
'Authorization': basicHeader
});
return this.http.get(url, { headers: headers }); // Error at this line
}
}
守着星空守着你
不负相思意
莫回无
相关分类