SpringBoot 静态资源 使用项目外部路径图片 跨域问题CORS 解决 been blocked by CORS policy header field authorization

配置类

package com.zz.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Value("${imagesPath}")
    private String mImagesPath;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if(mImagesPath.equals("") || mImagesPath.equals("${imagesPath}")){
            String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
            if(imagesPath.indexOf(".jar")>0){
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            }else if(imagesPath.indexOf("classes")>0){
                imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
            mImagesPath = imagesPath;
        }
        //LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+mImagesPath);
        registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
        // TODO Auto-generated method stub
        super.addResourceHandlers(registry);
    }
}

配置文件设置外面路径地址

application.properties

## 图片上传真是地址
imagesPath=file:/C:/upload/

测试 访问图片路径: http://localhost:9001/core/images/2.jpg

在这里插入图片描述

图片实际存放路径:C:\upload

在这里插入图片描述

SpringBoot2.X

Springboot2 里面WebMvcConfigurerAdapter 已经过时。

推荐使用接口 WebMvcConfigurer 。

package com.cy.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebAppConfig implements WebMvcConfigurer {

    @Value("${imagesPath}")
    private String mImagesPath;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if(mImagesPath.equals("") || mImagesPath.equals("${imagesPath}")){
            String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
            if(imagesPath.indexOf(".jar")>0){
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            }else if(imagesPath.indexOf("classes")>0){
                imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
            mImagesPath = imagesPath;
        }
        //LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+mImagesPath);
        registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
        // TODO Auto-generated method stub
    }
}


跨域问题CORS 统一处理

package com.zz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @Description: java类作用描述
 * @Author: Bsea
 * @CreateDate: 2019/10/9$ 21:33$
 */
@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*");//允许域名访问,如果*,代表所有域名
            }
        };
    }
}

错误日志:

:8080/#/pages/login/login:1 Access to XMLHttpRequest at ‘http://localhost:5557/xsz/api/user/login’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

解决办法


```java
package com.zz.util;

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "cors", urlPatterns = "/*")
@Configuration
public class CORSFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        if ("OPTIONS".equals(request.getMethod())) {
            res.getWriter().println("ok");
            response.setStatus( 200 );
            return;
        }
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {

    }
}




## 关注公众号,可以获取学习资料和源码
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200624163937211.jpg)
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CORS(跨源资源共享)是一种安全机制,用于限制从一个源加载的资源如何与来自另一个源的资源进行交互。当浏览器检测到请求的源、协议或端口与当前文档不同时,就会发出跨域请求。在这种情况下,服务器必须在响应中添加特定的CORS头部,以允许浏览器访问资源。如果请求头部中包含未经允许的字段,服务器将返回一个CORS错误,其中包含“has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.”的错误消息。 解决这个问题的方法是在服务器端添加允许请求头部的字段。在引用中提供了一个PHP的例子,其中添加了三个头部:Access-Control-Allow-Origin、Access-Control-Allow-Headers和Access-Control-Request-Headers。Access-Control-Allow-Origin头部指定允许访问资源的源,Access-Control-Allow-Headers头部指定允许的请求头部字段,Access-Control-Request-Headers头部指定浏览器在实际请求中发送的请求头部字段。 如果你使用的是axios或ajax进行请求,可以在请求头部中添加Authorization字段,如下所示: ```javascript axios({ method: 'get', url: 'http://example.com', headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' } }) ``` 在这个例子中,我们添加了Authorization和Content-Type字段到请求头部中。如果服务器允许这些字段,请求将被成功处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值