如何通过POST在Angular / Spring中注销

时间:2019-07-02 08:26:03

标签: java angular spring spring-boot spring-mvc

我想使用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
  }

  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 }); // Error at this line
  }
}

然后我收到错误消息:

(property) headers?: HttpHeaders | {
    [header: string]: string | string[];
}
Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
  Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.
    Index signature is missing in type 'Headers'.ts(2322)
http.d.ts(1086, 9): The expected type comes from property 'headers' which is declared here on type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'

return this.http.get(url, { headers: headers });

有人知道如何解决吗?

3 个答案:

答案 0 :(得分:1)

尝试像这样设置headers

let headers = new HttpHeaders();
headers = headers.set('x-auth-token', xToken).set('Authorization', basicHeader);

然后

return this.http.post(url, null, headers );

传递null,因为它接受第二个参数中的body

使用HttpClient

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

app.module.ts中:

import { HttpClientModule } from '@angular/common/http';

和@NgModule中: imports: [ HttpClientModule ]

答案 1 :(得分:1)

这是正常现象,默认情况下,@RequestMapping("/user/logout")仅接受GET个请求。您必须显式设置方法

@RequestMapping("/user/logout", method = RequestMethod.POST)
public ResponseEntity<String> logout(){
    SecurityContextHolder.clearContext();
    return new ResponseEntity<String>("Logout Successfully!", HttpStatus.OK);
}

或使用@PostMapping

答案 2 :(得分:1)

尝试一下:

constructor(private http:HttpClient){}
logout()
{
    const url = 'http://localhost:8181/user/logout';
    const headers = new HttpHeaders()
      .set('x-auth-token', localStorage.getItem('xAuthToken'));

    return this.http.post(url, '' ,{headers: headers, responseType: 'text'})};

在春季,我的建议是使用@PostMapping@DeleteMapping注释而不是@RequestMapping。将ResponseType用作“文本”的原因是因为您提供了ResponseEntity<>类型的String,并且默认情况下Angular将响应视为JSON。

此外,在订阅该可观察项时,请记住在响应中使用localStorage.removeItem('xAuthToken');,并在ngOnDestroy()生命周期中取消订阅该可观察项。