Explain Spring Boot 2.0. 2 + Ajax to solve the problem of cross domain request

  • 2021-07-02 23:59:50
  • OfStack

Problem description

The back-end domain name is A. abc. com, and the front-end domain name is B. abc. com. Cross-domain access occurs when the browser accesses. Browser restrictions on javascript's homology policy.

When HTTP is requested, the request itself returns 200, but the returned result does not follow success and is prompted in the browser console:

Cross-source requests blocked: The homology policy prevents reading remote resources at https://www. baidu. com/. (Reason: 'Access-Control-Allow-Origin' missing from CORS header).

Solutions

1.jsonp

2. Refer to js of A station

3. Nginx is the reverse agent of A station

4. Back-end services release cross-domain requests

Among them, the last two are common.

Detailed scheme

This article mainly describes the fourth solution: back-end services release cross-domain requests.

Releasing cross-domain requests in spring boot is straightforward.

1. Add 1 configuration class


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 *  Cross-domain access configuration 
 * @author wencst
 * @creation 2017 Year 8 Month 18 Day 
 */
@Configuration
public class CustomCORSConfiguration {
 private CorsConfiguration buildConfig() {
 CorsConfiguration corsConfiguration = new CorsConfiguration();
 corsConfiguration.addAllowedOrigin("*");
 corsConfiguration.addAllowedHeader("*");
 corsConfiguration.addAllowedMethod("*");
 return corsConfiguration;
 }
 @Bean
 public CorsFilter corsFilter() {
 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
 source.registerCorsConfiguration("/**", buildConfig());
 return new CorsFilter(source);
 }
}

With the addition of this class, non-homologous http access can proceed normally, but will there be any problems?

For most websites, cookie is still needed as the medium for data transmission at the front and back ends, but the default non-homologous request does not carry cookie information.

2. The server allows cookie information to be carried across domains

In spring boot 2.0. 2, allowing cross-domain settings is relatively simple, with only one configuration class added.


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 *  Cross-domain access configuration 
 * @author wencst
 * @creation 2017 Year 8 Month 18 Day 
 */
@Configuration
public class CustomCORSConfiguration {
 private CorsConfiguration buildConfig() {
 CorsConfiguration corsConfiguration = new CorsConfiguration();
 corsConfiguration.addAllowedOrigin("*");
 corsConfiguration.addAllowedHeader("*");
 corsConfiguration.addAllowedMethod("*");
 corsConfiguration.addExposedHeader("Content-Type");
 corsConfiguration.addExposedHeader( "X-Requested-With");
 corsConfiguration.addExposedHeader("accept");
 corsConfiguration.addExposedHeader("Origin");
 corsConfiguration.addExposedHeader( "Access-Control-Request-Method");
 corsConfiguration.addExposedHeader("Access-Control-Request-Headers");
 corsConfiguration.setAllowCredentials(true);
 return corsConfiguration;
 }
 @Bean
 public CorsFilter corsFilter() {
 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
 source.registerCorsConfiguration("/**", buildConfig());
 return new CorsFilter(source);
 }
}

After adding information, the AJAX request still needs to be adjusted at the front end to carry cookie information in non-homologous requests.

3. Front-end adjustment


$.ajax({
 url: 'http://beta.roboming.com/api.php?s=/Public/AdminLogin.html',
 type: 'POST',
 async:true,
 xhrFields:{
  withCredentials:true
 },
 data: {
  username:userName,
  password:pwd
 },
 success: function(respon){
  console.log(respon);
  var res=eval(respon);
 },
 error: function(){
  alert(' An error occurred on the server! ');
 }
});

At this time, when the front end makes a cross-domain request to the back-end service, increase


xhrFields:{
  withCredentials:true
},

You will bring cookie information, and you will bring token/sessionID and so on.

Test method

Add 1 controller to spring boot


@Controller
public class LoginController {
 @RequestMapping(value = "setString")
 @ResponseBody
 public String setString(HttpServletRequest request, HttpServletResponse response , @RequestParam String value) {
 request.getSession().setAttribute("username", value);
 return "OK";
 }
 @RequestMapping(value = "getString")
 @ResponseBody
 public String getString(HttpServletRequest request, HttpServletResponse response) {
 String username = (String)request.getSession().getAttribute("username");
 return username;
 }
}

Add 1 index. html to access cross-domain access.


<html>
<head>
<meta charset="utf-8">
<title> Cross-domain request </title>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<button onclick="set()">set</button>
<br><br>
<button onclick="get()">get</button>
<script>
function set(){
 $.ajax({
 url:'http://wencst.vicp.net/setString?value=10',
 xhrFields:{
  withCredentials:true
 },
 success:function(result){
 alert(result);
 }
 });
}
function get(){
 $.ajax({
 url:'http://wencst.vicp.net/getString',
 xhrFields:{
  withCredentials:true
 },
 success:function(result){
 alert(result);
 }
 });
}
</script>
</body>
</html>

The html file can be accessed locally alone, but it does not necessarily form service access.

When the server does not allow cross-domain access, the html file access reports an error and the call fails.

When the server allows cross-domain access, html requests access successfully.

When the server starts cookie delivery and adds in the html file xhrFields参数时,session生效 .


Related articles: