当前位置:网站首页>跨域的五种解决方案
跨域的五种解决方案
2022-08-10 12:09:00 【祁_z】
跟多介绍可参考:
跨域的五种解决方案笔记和相关资料下载
1. 什么是跨域
浏览器不允许执行其他网站的脚步(ajax),浏览器的同源策略造成的;
例如:发起ajax请求时如果IP、端口、协议任一不同,则都属于跨域。
例如以下案例中,A网站需要请求B网站接口:
| A网站 | B网站 | 是否跨域 | 说明 |
|---|---|---|---|
| http://192.162.1.1:8080 | http://192.162.2.2:8080 | 存在跨域 | IP不同 |
| http://192.162.1.1:8080 | http://192.162.1.1:8081 | 存在跨域 | 端口不同 |
| http://192.162.1.1:8080 | https://192.162.1.1:8080 | 存在跨域 | 协议不同 |
| http://192.162.1.1:8080 | http://192.162.1.1:8080 | 不存在跨域 | (协议、ip、端口)全部相同 |
2. 演示跨域问题
步骤:
首先在右上角下载本章节相关资料;
- 将demo.html 放入Nginx的html目录中_(默认已经放进去了)_,双击nginx.exe启动Nginx, –启动Nginx
- 运行jar包
java -jar kexuekt01.jar, 或通过idea打开kexuekt01项目, – 启动项目 - 浏览器访问:
http://127.0.0.1/demo.html– 看效果
F12打开浏览器控制台查看跨域error错误信息`:
重要知识点:存在跨域时Java接口是可以正常进行业务处理的,只是浏览器不能接收后台返回的数据,并在图 1浏览器控制台输出的跨域错误。
3. 解决跨域的五种方法
- jsonp
- 内部HttpClient远程调用
- nginx反向代理
- 设置响应头允许跨域 response.setHeader(“Access-Control-Allow-Origin”, “*”);
- SpringBoot注解@CrossOrigin
3.1 Jsonp解决跨域演示
前端代码
$.ajax({
type:"get",
dataType:"jsonp",
jsonp:"callback",//请求中重写回调函数的名字
url:"http://127.0.0.1:8080/kexue/user",
success:function (data) {
alert(data.response);
}
}, 'json');
后台代码
- 后台需要接收的jsonp:"callback"中的"callback"参数,
- 返回参数格式必须为:callback({object});
@RequestMapping("/kexue/user")
public String demo(String callback) {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", "调用成功");
// 返回格式:callback({object});
return callback + "(" + obj + ")";
}
说明
Jsonp的使用方式较为麻烦,解决跨域一般不会使用该方法。
3.2 内部HttpClient远程调用
启动两个后台
端口1:8080(自己公司的项目解决了跨域问题)
端口2:8081(模拟第三方项目接口,没有解决跨域问题)
8080端口项目
@CrossOrigin // 跨域注解
@RestController
public class Demo1 {
@RequestMapping("/kexue/user")
public JSONObject demo() {
String body = HttpRequest.get("127.0.0.1:8081/kexue/user2").execute().body();
JSONObject obj = JSONUtil.parseObj(body);
return obj;
}
}
8081端口项目(第三方接口)
@RequestMapping("/kexue/user2")
public JSONObject demo() {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", "第三方接口");
return obj;
}
注:修改端口号,便于测试 -Dserver.port=8081
说明
HttpClient这种方式适合调用第三方接口。
例如:调用第三方接口时,如果前端直接调用第三方接口会报跨域问题(第三方接口没有解决跨域问题),那么就只能通过后台HttpClient的方式进行调用。
3.3 Nginx反向代理
前端代码
$.ajax({
type:"get",
url:"http://127.0.0.1:80/kexue/user",
success:function (data) {
//请求成功后的处理
alert(data.response);
}
}, 'json');
后端代码
@RequestMapping("/kexue/user")
public JSONObject demo() {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", "调用成功");
// 返回格式:callback({object});
return obj;
}
nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
#拦截所有以/kexue开头的请求
location /kexue {
index proxy_set_header Host $host;
index proxy_set_header X-Real-IP $remote_addr;
index proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080; #后端服务地址
}
}
}
说明
使用Nginx方向代理的前提是,前端代码(vue)需要和Nginx服务在一台物理机上;如果满足以上条件,就优先考虑通过Nginx反向代理来解决跨域问题。
3.4 设置响应头允许跨域
前端代码
$.ajax({
type:"get",
url:"http://127.0.0.1:8080/kexue/user",
success:function (data) {
//请求成功后的处理
alert(data.response);
}
}, 'json');
后端代码
@RequestMapping("/kexue/user")
public JSONObject demo(HttpServletResponse response) {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", "调用成功");
// *允许所有网站跨域
response.setHeader("Access-Control-Allow-Origin", "*");
return obj;
}
说明
通常都是在拦截器中来配置“设置响应头允许跨域”。
3.5 @CrossOrigin注解
前端代码
$.ajax({
type:"get",
url:"http://127.0.0.1:8080/kexue/user",
success:function (data) {
//请求成功后的处理
alert(data.response);
}
}, 'json');
后端代码
@CrossOrigin // 跨域注解
@RestController
public class Demo1 {
@RequestMapping("/kexue/user")
public JSONObject demo() {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", "调用成功");
return obj;
}
}
说明
@CrossOrigin注解底层通过Spring的拦截器功能往response里添加 Access-Control-Allow-Origin等响应头信息。
response.setHeader(“Access-Control-Allow-Origin”, “*”);
个人博客首页 祁_z
原创不易,感觉对自己有用的话就️点赞收藏评论把。
边栏推荐
猜你喜欢

LeetCode中等题之比较版本号

【百度统计】用户行为分析

11 + chrome advanced debugging skills, learn to direct efficiency increases by 666%

数字藏品,“赌”字当头

mSystems | 中农汪杰组揭示影响土壤“塑料际”微生物群落的机制

燃炸!字节跳动成功上岸,只因刷爆LeetCode算法面试题

多线程下自旋锁设计基本思想

LeetCode简单题之合并相似的物品

Alibaba Cloud Jia Zhaohui: Cloud XR platform supports Bizhen Technology to present a virtual concert of national style sci-fi

如何让别人看不懂你的 JS 代码?把你当大佬!
随机推荐
Codeforces Round #276 (Div. 1) D. Kindergarten
【集合】HashSet和ArrayList的查找Contains()时间复杂度
神经网络学习-正则化
培训机构学习费用是多少呢?
Pod生命周期
Nanodlp v2.2/v3.0光固化电路板,机械开关/光电开关/接近开关的接法和系统状态电平设置
Excel function formulas - HLOOKUP function
Keithley DMM7510精准测量超低功耗设备各种运作模式功耗
Common examples of regular expressions
日记16
实践为主,理论为辅!腾讯大佬MySQL高阶宝典震撼来袭!
Overseas media publicity. What problems should domestic media pay attention to?
The god-level Alibaba "high concurrency" tutorial - basic + actual combat + source code + interview + architecture is all-inclusive
基于PLECS的离网(孤岛)并联逆变器的Droop Control下垂控制仿真
Does face attendance choose face comparison 1:1 or face search 1:N?
漏洞管理计划的未来趋势
phpstrom 快速注释:
没有接班人,格力只剩“明珠精选”
iTextSharp操作PDF
tommy's spell