什么是跨域

news/2024/7/5 2:49:33

目录

1 同源策略

2 什么是跨域

3 如何解决跨域

3.1 配置CROS

 3.2 Nginx解决跨域问题


1 同源策略

        跨域是指浏览器不能执行其他网站的脚本,是由浏览器的同源策略造成的,是浏览器加的安全限制。同源是指,域名,协议,端口均相同

2 什么是跨域

当请求的url和当前页面的url在域名、协议、端口三者之间有一个不相同就会产生跨域问题。

当前页面url被请求url是否跨域跨域原因
http://www.baidu.com/http://www.baidu.com/index.html域名、协议、端口都相同
http://www.baidu.com/https://www.baidu.com/index.html协议不同(http/https)
http://www.baidu.com/http://www.test.com/主域名不同(baidu/test)
http://www.baidu.com/http://blog.baidu.com/子域名不同(baidu/test)
http://www.baidu.com:8080/http://www.baidu.com:7890/端口不同(8080/7890)

3 如何解决跨域

这里介绍平时最常用的两种跨域解决方式 1配置CROS 2配置nginx

没有进行配置之前的代码:

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cors</title>
    <script type="text/javascript" src="jquery-3.5.0.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#cors-btn1").click(function () {
                $.ajax({
                    url: "http://localhost:9999/test/cros", //此时9999是后端服务器端口号
                    success: function (data) {
                        console.log(JSON.stringify(data));
                    }
                });
            });

        })
    </script>
</head>
<body>
<button id="cors-btn1">跨域测试test1</button>
</body>
</html>

后端代码:

@RestController
public class LoginController {

    @GetMapping("/test/cros")
    public String testCros(){
        return "测试解决跨域问题";
    }
}

直接在idea中打开浏览器访问:

 结果:出现跨域问题如下

3.1 配置CROS

前端代码不变、后端代码配置CROS,设置一个过滤器。

配置过滤器:

package com.liubujun.springbootinterceptor.filter;





import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: liubujun
 * @Date: 2022/10/16 19:26
 */

@WebFilter("/*")
public class MyFilterOne implements Filter {


    /**
     * web应用启动时,web服务器将创建Filter的实例对象,并调用init方法,读取web.xml的配置,完成对象的初始化功能,
     * 从而为后续的用户请求做好拦截的准备工作(filter对象只会创建一次,init方法也只会执行一次,开发人员通过init的参数,
     * 可或得代表当前filter配置信息的FilterConfig对象)
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 这个方法完成实际的过滤操作,当客户请求访问与过滤器相关联的URL的时候,Servlet过滤器将先执行doFilter方法,FilterChain参数用于访问后续过滤器
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("我是过滤器,我进来了");

        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpResponse.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpResponse.addHeader("Access-Control-Max-Age", "3600");

        httpResponse.addHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setStatus(HttpStatus.OK.value());
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * filter创建后会保存在内存中,当web应用移除或者服务器停止时才销毁,该方法在Filter的生命周期中仅执行一次,在这个方法中,可以释放过滤器使用的资源
     */
    @Override
    public void destroy() {

    }
}

启动类:

@SpringBootApplication
@ServletComponentScan
public class SpringbootInterceptorApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootInterceptorApplication.class, args);
    }
}

直接在浏览器打开:

 结果没有出现跨域问题

 3.2 Nginx解决跨域问题

打开自己nginx下的nginx.conf文件,向其中加入如下代码

    server {
        listen       8000;
        server_name  localhost;
        # / 表示匹配路径为/的url
        location / {
           proxy_pass http://localhost:9999;
        }
 
        # /user 表示访问以/test 开头 的地址 如/testname,/test/find等
        location /test {
           proxy_pass http://localhost:9999;
        }
 
    }

然后启动nginx:

前端代码也要做相应的修改: 

 

然后在浏览器端输入地址直接访问:http://localhost:8000/test/cros

就会转发成http://localhost:9999/test/cros

 

 


http://lihuaxi.xjx100.cn/news/125963.html

相关文章

【单片机】单片机的核心思想

&#x1f4ac;推荐一款模拟面试、刷题神器 、从基础到大厂面试题&#xff1a;&#x1f449;点击跳转刷题网站进行注册学习 目录 一、单片机的核心思想 二、单片机核心图 三、上拉电路及应用 排阻的优势 四、单片机的输入输出模式 1、接收外部电压信号 2、向外输出电压信…

STC51单片机学习笔记9——stc12c52 串口显示AD(单路ad+led指示灯)

stc12le5204ad 为8位AD //烧写程序时&#xff0c;一定要选用外部晶振&#xff08;烧写软件默认为内部晶振&#xff08;5M~6M&#xff09;&#xff09;,不然还会影响ADC //烧写时&#xff0c;有时候写不进去&#xff0c;尝试断开地线&#xff0c;然后接上上电 #include<reg5…

每天学习一点英语——number,amount,quantity区别、用法

文章目录amountamount为名词amount 作动词number用法quantity用法思考来源&#xff1a;看uptick的英文解释——an increase in the number or amount of sth&#xff0c;即n.小幅增加&#xff0c;上扬&#xff1b;改善例句&#xff1a;After the health examination&#xff08…

[祥云杯 2022] pwn2 leak

看了看雪的WP&#xff0c;第一次见这个东西&#xff0c;复现一下。 libc-2.27-3Ubuntu1.6-amd64 这个版本的libc禁用了3u1的直接double两次free的地址不能相同&#xff0c;并且_IO_2_1_stdout_头部也是清空的不能通过覆盖一个尾字节泄露地址&#xff0c;同时题目没有show。但…

Python Web开发-django搭建环境

这段时间 不太忙&#xff0c;想着整理一下python开发相关的内容&#xff0c;so 就现在&#xff0c;说整就整&#xff0c;白羊座行动派&#xff01; Django简介 Django&#xff0c;发音为[dʒŋɡəʊ]&#xff0c;是用python语言写的开源web开发框架&#xff0c;并遵循MVC设计…

机器学习从零到入门 逻辑回归详解

逻辑回归详解 从零开始 从理论到实践一、逻辑回归的理解1.1、字面含义1.2、引申1.2.1、阶跃函数的引入1.2.2、可导的阶跃函数 - Logistic函数1.2.3、Logistic回归1.2.4、回归系数的求解 - 极大似然估计二、sklearn的使用参考一、逻辑回归的理解 前面介绍了线性回归及其衍生回归…

MyBatis 动态SQL技术

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能。 sql 标签 <sql id"empColumns"> eid,ename,age,sex,did </sql> select <include refid"empColumns"></include> from t_emp可以记录一段公共sql片段&#x…

动手学深度学习(pytorch)2

动手学深度学习&#xff08;pytorch&#xff09;2概率库函数查阅线性神经网络线性回归概率 先抽样 import torch from torch.distributions import multinomial from d2l import torch as d2l fair_probs torch.ones([6]) / 6 tmultinomial.Multinomial(10, fair_probs).sam…