用行为解决TP5.1跨域问题 CORS

原理

1.CORS的概念

    CORS(Cross-Origin Resource Sharing 跨源资源共享),当一个请求 url 的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。

2. 跨域点

当浏览器检查到有跨域的问题,会对访问的接口做一个判断,如果是简单的接口,则直接访问,如果是复杂的接口,则需要先发送一个 option 请求,如果路由里面没有定义该接口的 option 请求,或者返回非200http状态码,就会报一个 404 错误。

3.PHP解决方法

 $allow_origin = array(
            'http://192.168.1.6',
            'http://www.bookadmin.com',
            'http://www.book.com'
        );
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        if(in_array($origin, $allow_origin)){
            header('Access-Control-Allow-Origin:'.$origin);
        }
        header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, OPTIONS,Cache-Control, Pragma, Authorization, Accept, Accept-Encoding');
        header('Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE');

或者全部允许

header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Headers:*');
        if (request()->isOptions()) {
            sendResponse('',200,'ok');
        }

一检查到跨域问题时,会有两次请求,第一次method是 option ,如果状态码200,才会进行具体请求。这里判断如果为option直接返回 200

Thinkphp5.1解决方式

1.你需要在你的BaseController里注册钩子(TP5官方也叫做添加行为标签位)

\think\Hook::listen('response_send');

行为定义

2.application->api->behavior->CORS.php

namespace app\index\behavior;

use think\facade\Session;
use think\Request;

/**
 * CORS跨域
 * Class CORS
 * @package app\index\behavior
 */
class CORS
{
    public function run()
    {// 响应头设置 我们就是通过设置header来跨域的 这就主要代码了 定义行为只是为了前台每次请求都能走这段代码
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Headers:*');
        header('Access-Control-Allow-Credentials:false');
        if (request()->isOptions()) {
            sendResponse('',200,'ok');
        }

    }


}

application/tags.php 文件,这个能保证加载全局的函数。

3. 绑定行为 绑定完才会去执行   在 application->tags.php 文件中添加如下代码:

return [
    // 应用初始化
    'app_init'     => [],
    // 应用开始
    'app_begin'    => [],
    // 模块初始化
    'module_init'  => [],
    // 操作开始执行
    'action_begin' => [],
    // 视图内容过滤
    'view_filter'  => [],
    // 日志写入
    'log_write'    => [],
    // 应用结束
    'app_end'      => [],
    'response_send' => [
        'app\\index\\behavior\\CORS'
    ],
];

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要使用Spring Security解决CORS跨域问题,可以按照以下步骤进行配置: 1. 添加CORS配置类:创建一个类,继承自`WebSecurityConfigurerAdapter`,并重写`configure(HttpSecurity http)`方法。 ```java @Configuration public class CorsConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOrigin("*"); // 允许所有来源 configuration.addAllowedMethod("*"); // 允许所有请求方法 configuration.addAllowedHeader("*"); // 允许所有请求头 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } } ``` 2. 启用CORS配置:在Spring Boot应用的入口类上添加`@EnableWebSecurity`注解。 ```java @EnableWebSecurity public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 通过以上配置,Spring Security会自动处理跨域请求,并允许所有来源、所有请求方法和所有请求头。你可以根据需要调整配置,例如指定允许的来源、方法和头部信息。 请注意,如果你的应用程序中使用了其他Spring Security配置,你需要将CORS配置类的优先级调整到较低的位置,以确保CORS配置被正确应用。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysnownet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值