Home Java javaTutorial How Springboot solves the cross-domain request problem of ajax custom headers

How Springboot solves the cross-domain request problem of ajax custom headers

May 16, 2023 pm 12:43 PM
ajax springboot headers

1. What is cross-domain

Due to the browser’s same-origin policy (same-origin policy), it is a well-known security policy proposed by Netscape. Now all browsers that support JavaScript All servers will use this strategy. The so-called same origin means that the domain name, protocol, and port are the same.). Any one of the protocol, domain name, and port used to send the request URL is different from the current page address, which is considered cross-domain.

For details, please check the following table:

How Springboot solves the cross-domain request problem of ajax custom headers

2. How springboot solves cross-domain problems

1. Ordinary cross-domain request solution:

①Add the annotation @CrossOrigin(origins = "http://127.0.0.1:8020", maxAge = 3600)

to the request interface Description: origins = "http://127.0.0.1:8020" The origins value is the domain currently requesting the interface

②General configuration (all interfaces allow cross-domain requests)

New A configuration class or add CorsFilter and CorsConfiguration methods in Application

@Configuration 
public class CorsConfig { 
  private CorsConfiguration buildConfig() { 
    CorsConfiguration corsConfiguration = new CorsConfiguration(); 
    corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
    corsConfiguration.addAllowedHeader("*"); // 2允许任何头
    corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等) 
    return corsConfiguration; 
  } 

  @Bean 
  public CorsFilter corsFilter() { 
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
    source.registerCorsConfiguration("/**", buildConfig()); // 4 
    return new CorsFilter(source); 
  } 
}
Copy after login

2. Cross-domain request of ajax custom headers

$.ajax({
    type:"GET",
    url:"http://localhost:8766/main/currency/sginInState",
    dataType:"JSON",
    data:{
      uid:userId
    },
    beforeSend: function (XMLHttpRequest) {
      XMLHttpRequest.setRequestHeader("Authorization", access_token);
    },
    success:function(res){
      console.log(res.code)
    }
  })
Copy after login

Request http at this time: The //localhost:8766/main/currency/sginInState interface found an OPTIONS http://localhost:8766/main/currency/sginInState 500 error. Ordinary cross-domain solutions cannot solve this problem. Why does an OPTIONS request appear?

How Springboot solves the cross-domain request problem of ajax custom headers

Reason

The browser will send a preflight request with method OPTIONS before sending the actual request. Preflighted requests This The request is used to verify whether this request is safe, but not all requests will be sent and need to meet the following conditions:

•The request method is not GET/HEAD/POST
•Content-Type of the POST request Not application/x-www-form-urlencoded, multipart/form-data, or text/plain

•The request sets a custom header field

For the management interface, I have the The interface performs permission verification. Each request needs to carry a custom field (token) in the header, so the browser will send an additional OPTIONS request to verify the security of this request.

Why is the OPTIONS request 500?

OPTIONS request will only carry custom fields and will not bring the corresponding values ​​in. When the token field is verified in the background, the token is NULL, so the verification fails and a abnormal.

So let’s solve this problem now:

① Add

spring:
to the spring boot project application.yml mvc:
dispatch-options-request: true

Note: This solution may not solve the OPTIONS problem in some cases. The reason may be environmental issues or complex Custom filter filter configuration issues, etc.

②Add filter configuration

Step 1: Handwritten RequestFilter request filter configuration class This class needs to implement the HandlerInterceptor class, which is under org.springframework.web.servlet.HandlerInterceptor.

Specific code implementation:

@Component
public class RequestFilter implements HandlerInterceptor {
  public boolean preHandler(HttpServletRequest request,HttpServletResponse response,Object handler){
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "86400");
    response.setHeader("Access-Control-Allow-Headers", "Authorization");
    // 如果是OPTIONS请求则结束
    if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
      response.setStatus(HttpStatus.NO_CONTENT.value());
      return false;
    }
    return true;
  }
}
Copy after login

Step 2: Handwriting MyWebConfiguration This class needs to inherit WebMvcConfigurationSupport.

Note: WebMvcConfigurationSupport is version 2.x or above, and version 1.x is WebMvcConfigurerAdapter.

Specific code implementation:

@Component
public class MyWebConfiguration extends WebMvcConfigurationSupport{
  @Resource
  private RequestFilter requestFilter;
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 跨域拦截器
    registry.addInterceptor(requestFilter).addPathPatterns("/**");
  }
}
Copy after login

The above is the detailed content of How Springboot solves the cross-domain request problem of ajax custom headers. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

What are the differences between SpringBoot and SpringMVC? What are the differences between SpringBoot and SpringMVC? Dec 29, 2023 am 10:46 AM

What is the difference between SpringBoot and SpringMVC? SpringBoot and SpringMVC are two very popular Java development frameworks for building web applications. Although they are often used separately, the differences between them are obvious. First of all, SpringBoot can be regarded as an extension or enhanced version of the Spring framework. It is designed to simplify the initialization and configuration process of Spring applications to help developers

See all articles