OPTIONS API仅在首次在服务器上加载应用程序时被调用一次



OPTIONS API在我第一次启动服务器时只被调用一次,状态代码为200,如果我再次刷新页面,则只调用GET API,或者如果我停止服务器,然后重新启动服务器,则也调用GET API,而不是OPTIONS API。当我们第一次加载应用程序时调用OPTIONS API也是如此,但根据我的理解,当我们有弹簧安全性时,应该在任何其他API调用之前首先调用OPTIONS API

HelloWorldController.java

@CrossOrigin(origins="http://localhost:4200")
@RestController
public class HelloWorldController {
@GetMapping(path="/hello/path-variable/{name}")
public HelloWorldBean helloVariable(@PathVariable String name) {
return  new HelloWorldBean(String.format("Hello message %s",name));
}}

SpringSecurityConfigurationBasicAuth.java

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
.anyRequest().authenticated()
.and()
//.formLogin().and()
.httpBasic();
}
}

welcome-data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
export class helloWorldBean{
constructor( public message:string){
}
}
@Injectable({
providedIn: 'root'
})
export class WelcomeDataService {
constructor(private http:HttpClient) {

}

executeHelloWorldBeanServicePathVarible(name)
{
let basicAuthHeaderString=this.createBasicAuthenticationHttpHeader();
let headers = new HttpHeaders({
Authorization: basicAuthHeaderString
})
return this.http.get<helloWorldBean>
(`http://localhost:8080/hello/path-variable/${name}`, {headers});
}
createBasicAuthenticationHttpHeader(){
let username='user'
let password='dummy'
let basicAuthHeaderString='Basic ' + window.btoa(username + ':' + password);
return basicAuthHeaderString;
} 
}

网络日志

Request URL: http://localhost:8080/hello/path-variable/user
Request Method: GET
Status Code: 200 
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade

响应:

{"message":"Hello message user"}

飞行前请求或OPTIONS调用会根据浏览器缓存一定的持续时间。它由Access Control Max Age标头属性控制。

当你第一次启动服务器并点击url时,浏览器会调用OPTIONS方法调用来获取允许的方法等。但它随后会被缓存,随后的请求必须使用该缓存。

如果你不想使用缓存,它的值应该设置为-1。

Access-Control-Max-Age: -1

有关此标头参数的更多信息,请点击此处-

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age#:~:text=%20Access%2DControl%2DMax%2D,Headers%20headers

我相信你可以简单地在CorsRequest注释中设置maxAge,这将为你设置这样的Header参数-

@CrossOrigin(origins="http://localhost:4200", maxAge=-1)
@RestController
public class HelloWorldController {

这将禁用缓存,所有请求都将调用Preflight请求。

最新更新