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

Java 如何通过POST在Angular/Spring中注销,java,angular,spring,spring-boot,spring-mvc,Java,Angular,Spring,Spring Boot,Spring Mvc,我想用POST方法注销,下面是我的代码: logout() { const url = 'http://localhost:8181/user/logout'; const xToken = localStorage.getItem('xAuthToken'); const basicHeader = 'Basic ' + localStorage.getItem('credentials'); const headers = new Headers({

我想用POST方法注销,下面是我的代码:

  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);
}
如果我使用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
  }
}
let headers = new HttpHeaders();
headers = headers.set('x-auth-token', xToken).set('Authorization', basicHeader);
然后我得到错误消息:

(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; }'
在第
行返回this.http.get(url,{headers:headers})


有人知道如何修复它吗?

尝试如下设置
标题:

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
  }
}
let headers = new HttpHeaders();
headers = headers.set('x-auth-token', xToken).set('Authorization', basicHeader);
然后呢,

return this.http.post(url, null, headers );
传递
null
,因为它接受第二个参数中的
body

使用HttpClient

从'@angular/common/http'导入{HttpClient}

构造函数(私有http:HttpClient){}

在app.module.ts中:

从'@angular/common/http'导入{HttpClientModule}

在@NgModule中:
imports:[HttpClientModule]
这是正常的,默认情况下
@RequestMapping(“/user/logout”)
只接受
GET
请求。您必须显式地设置该方法

@RequestMapping("/user/logout", method = RequestMethod.POST)
public ResponseEntity<String> logout(){
    SecurityContextHolder.clearContext();
    return new ResponseEntity<String>("Logout Successfully!", HttpStatus.OK);
}
@RequestMapping(“/user/logout”,method=RequestMethod.POST)
公共响应注销(){
SecurityContextHolder.clearContext();
返回新的响应状态(“成功注销!”,HttpStatus.OK);
}
或者使用
@PostMapping

尝试以下操作:

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.removietem('xAuthToken')以及取消订阅
ngondestry()
生命周期中的可观察内容。

我已经尝试过,但出现错误
类型“HttpHeaders”缺少类型“Headers”中的以下属性:forEach、值、toJSON、条目、mayBeSetNormalizedNamets(2739)
。如果我改为
,则返回这个.http.post(url、标题、null)
,我遇到了同样的错误。你能确认你正在使用
HttpClientModule
这个。http
-->请显示你的构造函数
(http:HttpClientModule)
@mrSmith91 post存在于HttpClientModule中,可能有一些语法问题我没有骗你。我为您粘贴错误消息:
属性“post”在类型“HttpClientModule”.ts(2339)
上不存在,那么
Http
HttpClient
之间有什么区别呢?我在构造函数中使用了
private http:http
,但是现在我需要为使用POST方法定义另一个
private http:HttpClient
?为什么我不能从
http
HttpClient
http
模块获取POST和get方法?模块是一个弃用的模块,
HttpClient
模块是
http
模块的改进替代品。对于所有类型的请求,无论是GET、POST、PUT、PATCH还是DELETE,都必须使用httpClient。HttpClient模块是在4.3中引入的,它有许多优点,例如进程事件、中间件逻辑的拦截器。结论是使用
HttpClient
而不是
Http
,因为Angular Team不赞成使用
HttpClient
,但还存在其他问题。我已经在我的帖子上更新了我的代码。如果可能,请查看并帮助我。标头是http模块的一部分,也不推荐使用。因此,现在您需要以这种方式设置头:new HttpHeaders().set('name',value')例如,在sendCredential()中,您必须使用
const headers=new HttpHeaders().set('Content Type','application/x-www-form-urlencoded').set('Authorization',basicHeader);返回this.http.get(url,{headers:headers})很好,但是我得到了这个错误
localStorage.setItem('xAuthToken',res.json().token)因为类型“Object”上不存在属性“json”。
?我已更改为
res.toString()
,但不起作用。你能发布你的
组件
代码吗?您呼叫的是
登录服务