在Angular 2中,可以使用withCredentials
属性来控制是否在后续请求中传递JSESSIONID。默认情况下,该属性是禁用的,因此需要手动启用。
以下是一个示例代码,展示如何在Angular 2中启用withCredentials
属性来传递JSESSIONID:
在服务端创建一个名为CorsConfig.java
的类,用于允许跨域请求:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowCredentials(true)
.maxAge(3600);
}
};
}
}
在Angular的HTTP请求中,设置withCredentials
属性为true
,以启用在后续请求中传递JSESSIONID:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MyService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('http://example.com/api/data', { withCredentials: true });
}
}
在上述示例中,http.get
方法的第二个参数是一个配置对象,通过将withCredentials
属性设置为true
,可以在后续请求中自动传递JSESSIONID。
请确保服务器端已正确配置允许跨域请求,并允许在请求中传递JSESSIONID。
上一篇:Angular 2与NgRx