Layui文件上传踩坑

Layui文件上传踩坑:

1.返回必须是json格式的问题

image-20210311221648448

按照layui规定前后端数据格式保持json格式

解决方案:

1.controller层方法上加@ResponseBody

2.在controller层方法中将对象转为json格式后返回,例如JSONObject.toJSONString(resObj);

2.跨域问题(CORS)

CORS,常被大家称之为跨越问题,准确的叫法是跨域资源共享(CORS,Cross-origin resource sharing),是W3C标准,是一种机制,它使用额外的HTTP头来告诉浏览器 让运行在一个 origin (domain) 上的Web应用被准许访问来自不同源服务器上的指定的资源。当一个资源从与该资源本身所在的服务器不同的域或端口请求一个资源时,资源会发起一个跨域 HTTP 请求。

例如 http://localhost:9000请求http://localhost:8761/eureka/apps就是违背了上述原则,即:请求服务器不同端口的另一个资源,出于安全原因,浏览器限制发起的跨源HTTP请求,例如,XMLHttpRequest和Fetch API遵循同源策略, 这意味着使用这些API的Web应用程序只能从加载应用程序的同一个域请求HTTP资源,除非使用CORS头。跨域资源共享( CORS )机制允许 Web 应用服务器进行跨域访问控制,从而使跨域数据传输得以安全进行。浏览器支持在 API 容器中(例如 XMLHttpRequest 或 Fetch )使用 CORS,以降低跨域 HTTP 请求所带来的风险。

CORS标准新增了一组 HTTP 头字段(Access-Control-Allow-Origin),允许服务器声明哪些源通过浏览器有权限访问哪些资源。另外,规范要求,对那些可能对服务器数据产生副作用的 HTTP 请求方法(特别是 GET以外的 HTTP 请求,或者搭配某些 MIME 类型的 POST请求),浏览器必须首先使用 OPTIONS 方法发起一个预检请求(preflight request),从而获知服务端是否允许该跨域请求。服务器确认允许之后,才发起实际的 HTTP 请求。在预检请求的返回中,服务器端也可以通知客户端,是否需要携带身份凭证(包括Cookies 和 HTTP 认证相关数据)。

解决办法:

在本项目中添加如下过滤器

  /**
   \* 解决跨域问题
   */
  public class AccessControlAllowOriginFilter implements Filter {
   
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
      HttpServletResponse response = (HttpServletResponse) res;
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Credentials", "true");
   
       chain.doFilter(req, response);
    }
   
    public void init(FilterConfig filterConfig) {
   
    }
   
    public void destroy() {
   
    }
   
  }

注解方式

在Spring Boot中拥有大量的注解,针对跨域问题,也提供了对应的注解@CrossOrigin,使用方法如下:

  import java.util.HashMap;

  import org.springframework.web.bind.annotation.CrossOrigin;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
  import org.springframework.web.bind.annotation.RequestParam;
  import org.springframework.web.bind.annotation.RestController;

  /**
   \* @author xcbeyond
   */
  @RestController
  @RequestMapping(value = "/api", method = RequestMethod.POST)
  public class DemoController {
       
    @CrossOrigin(origins = "*")
    @RequestMapping(value = "/get")
    public String get() {
      ……
    }
  }
posted @ 2021-03-11 22:28  夏小皮  阅读(1045)  评论(0编辑  收藏  举报