Java(一百四十九)SpringBoot前后端分离配置(跨域)

52 阅读1分钟

今天我们来学习SpringBoot框架前后端分离配置,这个主要就是配置跨域。

 

前后端分离简单讲就是

 

前端只编写页面

http://localhost:63342/demo/Java/webProgramIDEA/demo/index.html?_ijt=62k68adlarosiro34njc1vchb3&_ij_reload=RELOAD_ON_SAVE

 

后端编写Controller

http://localhost:7099/selectByExample

 

终于学到正题了,java是一个后端语言,现在前端框架这么发达,java就干点后端的事就行了,学什么jsp,写什么前端。

 

我这里接口还是使用之前写好的接口,代码如下:

@RequestMapping("selectByExample")
 @ResponseBody
 public List<User> selectByExample()
 {
     // 输出日志信息
     logger.info("selectByExample,info:");
     logger.trace("selectByExample,trace:");
     logger.debug("selectByExample,debug:");
     logger.warn("selectByExample,warn:");
     logger.error("selectByExample,error:");
     List<Userlist = userDao.selectByExample(null);
     return list;
 }

随意找一个地方写一个index.html文件

1.jpg

代码如下:

<html>
 <head>
     <title>Title</title>
 </head>
 <body>
 <h2>CAMELLIA</h2>
 <h3 id="h3"></h3>
 </body>
 </html>
 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
 <script>
     $(document).ready(function()
     {
         $.ajax({
             url:"http://localhost:7099/selectByExample",
             type:"get",
             success:function(response){
                 console.log(response)
                 $("#h3").html(response);
             }
         });
     });
 </script>

 

我们来访问index.html,结果如下图所示:

2.jpg

控制台报错跨域:

Access to XMLHttpRequest at 'http://localhost:7099/selectByExample' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

那接下来,我们需要在SpringBoot中配置跨域。那我们该怎么做呢?

在javaconfig中配置,文件位置如下图所示:

3.jpg

 

代码如下所示:

package com.example.demo.demos.web.config;
 
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.CorsRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 
 @Configuration
 public class CrosConfig extends WebMvcConfigurationSupport {
     @Override
     protected void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/**")
                 .allowedOrigins("*")
                 .allowedMethods("GET""HEAD""POST","PUT""DELETE""OPTIONS")
                 .allowedHeaders("*")
                 .exposedHeaders("access-control-allow-headers",
                         "access-control-allow-methods",
                         "access-control-allow-origin",
                         "access-control-max-age",
                         "X-Frame-Options")
                 .allowCredentials(false).maxAge(3600);
         super.addCorsMappings(registry);
     }
 }

跨域这就配置完成了。

 

我们再来访问index.html,结果如下图所示:

4.jpg

 

跨域问题解决了。

 

至此,SpringBoot的跨域配置完成。

 

有好的建议,请在下方输入你的评论。