Python项目配置ajax跨域:
class BaseHandler(tornado.web.RequestHandler):
# 解决跨域问题
def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Max-Age', 1000)
# self.set_header('Content-type', 'application/json')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
self.set_header('Access-Control-Allow-Headers', #'*')
'authorization, Authorization, Content-Type, Access-Control-Allow-Origin, '
'Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')
# 正常的Python后台请求代码
# class TestHandler(tornado.web.RequestHandler):
# 配置跨域的后台请求代码
class TestHandler(BaseHandler):
def get(self):
self.write("测试跨域")
Spring Boot项目配置ajax跨域:
package com.test.config;
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;
/**
* @version 1.0
* @author:yangping
* @create 2020/6/18 11:07
* @description 解决前后台对接跨域问题
* 在springboot项目的config目录下添加该类,即可实现ajax跨域
*/
@Configuration
public class CorssConfig {
// 设置允许跨域的源
private static String[] originsVal = new String[]{
"127.0.0.1:8085",
"localhost:8080",
// "google.com"
};
/**
* 跨域过滤器
*
* @return
*/
@Bean
public CorsFilter corsFilter() {
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);
}
}
}