When a cross-domain request is made, the backend requires token to be put into the header. How to solve it?

static page, you need to call the backend API (the backend and frontend are not put together and need to be cross-domain). The backend requires token to write the request API in header. How to write the query code?

Feb.28,2021

   $.ajax({
        url:httpUrl,
        type: 'get',
        data: {},
        beforeSend: function(request){
            request.setRequestHeader("token", "xxxx");
        },
        dataType: 'json',
        success: function(data){
            console.log(data);
        },
        error: function(error){
            console.log(error)
        }
    });

the above is front-end request processing.
the following is the backend (java) processing:

@Configuration
    public class CorsConf {
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.addAllowedOrigin("*");
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", corsConfiguration);
            return new CorsFilter(source);
        }
    }

get the xhr object, call the setHeader method
of xhr or the framework is generally encapsulated. Just pass header directly


setting header token of ajax


axios:

axios.interceptors.request.use(config => {
   config.headers = {
      'X-token': token
   }
  
  return config
}, err => {
  return Promise.reject(err)
})

so that token can be included in each request header.

Menu