简体   繁体   English

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

[英]OPTIONS API is only getting called once when Application is loaded for first time on server

OPTIONS API is getting called with 200 status code only once when I start the server first time and if I refresh the page again then only GET API is called or if I stop the server and then restart the server then also GET API is called and not OPTIONS API.So is OPTIONS API is called once we load the application first time but as per my understanding when we have spring security then OPTIONS API should be called first before any other API call OPTIONS API 仅在我第一次启动服务器时调用一次 200 状态代码,如果我再次刷新页面,则只调用 GET API,或者如果我停止服务器然后重新启动服务器,则调用 GET API 而不是OPTIONS API。所以,一旦我们第一次加载应用程序,就会调用 OPTIONS API,但根据我的理解,当我们有 Spring Security 时,应该先调用 OPTIONS API,然后再调用任何其他 API

HelloWorldController.java 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 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欢迎-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;
  } 
}

Network logs网络日志

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

Response:回复:

{"message":"Hello message user"}

The pre-flight request or the OPTIONS call is cached for certain duration depending upon the browser.根据浏览器的不同,飞行前请求或 OPTIONS 调用会被缓存一段时间。 It is controlled by Access-Control-Max-Age header property.它由 Access-Control-Max-Age 标头属性控制。

The first time you start the server and hit the url, browser will invoke OPTIONS method call to fetch the allowed methods etc. But it is then cached and the subsequent requests must be using this cache.第一次启动服务器并点击 url 时,浏览器将调用 OPTIONS 方法调用以获取允许的方法等。但它随后被缓存,后续请求必须使用此缓存。

If you don't want to use the cache, it's value should be set to -1.如果您不想使用缓存,则应将其值设置为 -1。

Access-Control-Max-Age: -1

More Information about this header parameter is here -有关此标头参数的更多信息在这里 -

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

I believe you can simply set the maxAge in CorsRequest annotation and this will set the Header Parameter for you like this -我相信您可以简单地在 CorsRequest 注释中设置 maxAge,这将像这样为您设置 Header 参数 -

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

This should disable the cache and all requests will call the Preflight request.这应该禁用缓存,所有请求都将调用预检请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使我在 android 中的给定时间间隔内请求更新,融合位置 api 的 OnLocationResult 也只调用一次 - OnLocationResult of fused Location api is only called once even when i have requested updates in given time interval in android 当代码仅说一次时,Java JOptionPane.showInputDialog()被多次调用 - Java JOptionPane.showInputDialog() getting called more than once when code only says once TextView:onDraw仅被调用一次 - TextView: onDraw getting called only once mouseMoved事件似乎只被调用一次 - mouseMoved event seems to only be getting called once 如何在更新后首次打开应用程序时仅启动一次活动? - How to launch activity only once when app is opened for first time after an update? 第一次显示时仅加载一次标签(片段),并将其保留以备后用 - Load tab (Fragment) only once when it is shown for the first time and retain it for later use 没有调用HTTP调用,只有OPTIONS请求正在进行Angular 4 - HTTP Call are not getting called only OPTIONS request are going Angular 4 a4j:support 函数在 h:commandLink 中只被调用一次 - a4j:support function getting called only once in h:commandLink Java,制作一次只能调用一次的方法 - Java, Make a method that can only be called once at a time 在Fragment中首次调用时,SharedPreferences为空 - SharedPreferences are empty when called for the first time in Fragment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM