1.JSON
原理:利用<script>标签无跨域属性,将请求的地址和数据通过src传递到后台,参数中添加回调函数,后台接收到回调函数后,再把回调函数添加返回数据作为参数回传到客户端
缺点:所有的script src请求都是资源文件请求,也就是都是get请求,无法实现post请求
客户端
<script src="jquery.js"></script>
$.ajax({
url:"http://192.168.0.222:8888/list",
methods:"get",
dataType:"jsonp", //执行jsonp请求,很重要
success:(res) => {
console.log(res);
}
})
2.CORS(cross-origion-resource-sharing) 跨域资源共享(服务端)
由http头决定浏览器是否接收前端发送跨域请求之后响应过来的结果
服务端添加拦截器,设置访问规则
//以java代码为例,添加CorsConfig.java类,
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigurer()
{
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").
allowedOrigins("*"). //允许跨域的域名,可以用*表示允许任何域名使用
allowedMethods("*"). //允许任何方法(post、get等)
allowedHeaders("*"). //允许任何请求头
allowCredentials(true). //带上cookie信息
exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
};
}
}
3.proxy(代理:在本地创建一个虚拟的中转服务器)
以VUE项目为例,在项目根目录创建vue.config.js
module.exports={
devServer:{
host: 'localhost',
port: 8082, //前端项目运行端口
proxy: {
'/api': {
target:'http://10.37.3.25:8089', // 你请求的第三方接口
//target:'http://localhost:8089', // 你请求的第三方接口
changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite:{ // 路径重写,
'^/api': '' // 替换target中的请求地址,也就是说以后你在请求地址的时候直接写成/api即可。
}
}
}
}
}