1. 程式人生 > 其它 >vue跨界域名報錯,後臺解決方法(未實測,僅供參考)

vue跨界域名報錯,後臺解決方法(未實測,僅供參考)

package com.foen.framework.config;
import javax.servlet.*;

import com.foen.common.utils.StringUtils;
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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * vue跨界域名報錯
 * @Autor:gzh
 * implements Filter
 */
//@Configuration
public class CrosConfig{
    private CorsConfiguration buildConfig(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");//1。允計任何域名使用
        corsConfiguration.addAllowedHeader("*");//2。允計任何頭
        corsConfiguration.addAllowedMethod("*");//3。允計任何方法
        return corsConfiguration;
    }

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

    /**
    @Override
    public void doFilter(ServletRequest res, ServletResponse req, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        // 不使用*,自動適配跨域域名,避免攜帶Cookie時失效
        String origin = request.getHeader("Origin");
        if(StringUtils.isNotBlank(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        }

        // 自適應所有自定義頭
        String headers = request.getHeader("Access-Control-Request-Headers");
        if(StringUtils.isNotBlank(headers)) {
            response.setHeader("Access-Control-Allow-Headers", headers);
            response.setHeader("Access-Control-Expose-Headers", headers);
        }

        // 允許跨域的請求方法型別
        response.setHeader("Access-Control-Allow-Methods", "*");
        // 預檢命令(OPTIONS)快取時間,單位:秒
        response.setHeader("Access-Control-Max-Age", "3600");
        // 明確許可客戶端傳送Cookie,不允許刪除欄位即可
        response.setHeader("Access-Control-Allow-Credentials", "true");

        chain.doFilter(request, response);

    }


    @Override
    public void destroy() {
    }**/
}