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

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

  }

}


慕码人8056858
浏览 78回答 3
3回答

守着星空守着你

headers尝试这样设置:let&nbsp;headers&nbsp;=&nbsp;new&nbsp;HttpHeaders(); headers&nbsp;=&nbsp;headers.set('x-auth-token',&nbsp;xToken).set('Authorization',&nbsp;basicHeader);进而,return&nbsp;this.http.post(url,&nbsp;null,&nbsp;headers&nbsp;);null按照它body在第二个参数中接受的方式传递。使用 HttpClient:import { HttpClient } from '@angular/common/http';constructor(private http: HttpClient) { }在 app.module.ts中:import { HttpClientModule } from '@angular/common/http';在@NgModule 中:&nbsp;imports: [ HttpClientModule ]

不负相思意

这很正常,默认情况下@RequestMapping("/user/logout")只接受GET请求。您必须明确设置方法@RequestMapping("/user/logout", method = RequestMethod.POST)public ResponseEntity<String> logout(){&nbsp; &nbsp; SecurityContextHolder.clearContext();&nbsp; &nbsp; return new ResponseEntity<String>("Logout Successfully!", HttpStatus.OK);}或者使用@PostMapping

莫回无

尝试这个:constructor(private http:HttpClient){}logout(){&nbsp; &nbsp; const url = 'http://localhost:8181/user/logout';&nbsp; &nbsp; const headers = new HttpHeaders()&nbsp; &nbsp; &nbsp; .set('x-auth-token', localStorage.getItem('xAuthToken'));&nbsp; &nbsp; return this.http.post(url, '' ,{headers: headers, responseType: 'text'})};在 Spring 中,我的建议是使用@PostMappingor @DeleteMappingannotation 而不是@RequestMapping. 使用 as 'text' 的原因ResponseType是因为您提供的是ResponseEntity<>as ofString类型,并且默认情况下 Angular 将响应视为 JSON。localStorage.removeItem('xAuthToken');此外,请记住在订阅该可观察对象时在响应中使用,并在ngOnDestroy()生命周期中取消订阅该可观察对象。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java