欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ajax跨域访问

程序员文章站 2022-06-03 23:13:59
...
No 'Access-Control-Allow-Origin' header is present on the requested resource.

在请求的java方法中加入 
ServletActionContext.getResponse().setHeader("Access-Control-Allow-Origin", "*");
即可

response.setHeader("Access-Control-Allow-Origin", "*");


参考:http://bbs.csdn.net/topics/390650335?page=1


接口跨域访问完全解决方案(java五种跨域解决方案)

解决 "Access-Control-Allow-Methods 列表中不存在请求方法 DELETE" 错误


Springboot统一跨域配置

import lombok.extern.slf4j.Slf4j;
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;

/**
 * 跨域配置
 */
@Configuration
@Slf4j
public class CorsConfig {
    // 设置允许跨域的源
    private static String[] originsVal = new String[]{
            "127.0.0.1:8080",
            "localhost:8080",
            "desktop.jdcloud.com"
    };

    /**
     * 跨域过滤器
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        log.info("corsFilter already execute.");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        this.addAllowedOrigins(corsConfiguration);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.addAllowedOrigin("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

    private void addAllowedOrigins(CorsConfiguration corsConfiguration) {
        for (String origin : originsVal) {
            corsConfiguration.addAllowedOrigin("http://" + origin);
            corsConfiguration.addAllowedOrigin("https://" + origin);
        }
    }
}