127还是localhost....?

前几天刚发现了一跨域问题,本来吧跨域问题也挺好解决的。

网上搜点教程,该怎么配置就怎么配置就完事了。

但是今天这个跨域问题有点棘手,问题就出在127.0.0.1还是localhost上面

先放一下一开始在127.0.0.1解决跨域的代码

前端

复制代码
```HTML
<!DOCTYPE html>
<html lang="en">


<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax Requests</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>


<body>
    <button id="sendPostRequest">Send Post Request</button>
    <button id="sendGetRequest">Send Get Request</button>


    <script>


            $("#sendPostRequest").click(function () {
                var stringValue = "caiyi";
                $.ajax({
                    type: "POST",
                    withCredentials: true,
                    xhrFields: { withCredentials: true },
                    url: "http://localhost:8081/testPost",
                    data: "username=" + encodeURIComponent(stringValue),
                    success: function (response) {
                        console.log(response);
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });


            $("#sendGetRequest").click(function () {
                var customParam = "caiyi";
                $.ajax({
                    type: "GET",
                    withCredentials: true,
                    xhrFields: { withCredentials: true },
                    url: "http://localhost:8081/testGet/caiyi",
                    success: function (response) {
                        console.log(response);
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });


    </script>
</body>


</html>

后端

复制代码
package com.example.springmvcdemo.config;

import org.springframework.beans.factory.annotation.Value;
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;


@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsFilter corsFilter() {

        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOrigin("http://127.0.0.1:5500/");
        //是否发送 Cookie
        config.setAllowCredentials(true);
        //放行哪些请求方式
        config.addAllowedMethod("*");
        //放行哪些原始请求头部信息
        config.addAllowedHeader("*");
        //暴露哪些头部信息
        config.addExposedHeader("*");
        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }
}

接口:

复制代码
package com.example.springmvcdemo.web;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
public class TestController {

    @PostMapping("/testPost")
    public String test(@RequestParam String username, HttpSession session){
        System.out.println(username);
        System.out.println(session);
        if (username != null){
            System.out.println(username);
            session.setAttribute(username,"测试session属性");
            System.out.println("测试获取:"+session.getAttribute(username));
            return "ok";
        }
        return "err";
    }
    @GetMapping("/testGet/{username}")
    public String test(HttpSession session, @PathVariable String username){
        System.out.println(username);
        System.out.println(session);
        System.out.println("get请求:"+session.getAttribute(username));
        return "ok";
    }
}

但是问题就在于两次请求前端并没有带上自身的cookie,通过查看请求可以发现请求回来的sessionid是不同的

而且控制台打印出来的session对象也不是一个,但是!但是来了:

这里先科普下cors:

CORS (Cross-Origin Resource Sharing,跨域资源共享)是一个系统,它由一系列传输的HTTP头组成,这些HTTP头决定浏览器是否阻止前端 JavaScript 代码获取跨域请求的响应。

同源安全策略 默认阻止"跨域"获取资源。但是 CORS 给了web服务器这样的权限,即服务器可以选择,允许跨域请求访问到它们的资源。

  • Access-Control-Allow-Origin
  • 指示请求的资源能共享给哪些域。
  • Access-Control-Allow-Credentials
  • 指示当请求的凭证标记为 true 时,是否响应该请求。

当我打开控制台查看响应头的时候会发现这两个属性是被设置了的,这就说明我们的后端cors配置已经生效了!

但是为什么会不好使呢?

于是我经过各种百度之后怀疑会不会是127.0.0.1这个域名的问题,于是吧前端启动的服务端口由127.0.0.1改到localhost,并修改对应的后端cors跨域配置

问题出奇的解决了,但我百思不得其解

修改后的后端代码:

复制代码
package com.example.springmvcdemo.config;

import org.springframework.beans.factory.annotation.Value;
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;


@Configuration
public class GlobalCorsConfig {

    @Bean
    public CorsFilter corsFilter() {

        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOrigin("http://localhost:5500/");
        //是否发送 Cookie
        config.setAllowCredentials(true);
        //放行哪些请求方式
        config.addAllowedMethod("*");
        //放行哪些原始请求头部信息
        config.addAllowedHeader("*");
        //暴露哪些头部信息
        config.addExposedHeader("*");
        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }
}

希望路过的各路大神可以指点一下,初步怀疑可能是springmvc的跨域配置不支持127.0.0.1,或者浏览器的同源策略有什么其他的隐形附加条件(已迷茫)

相关推荐
程序饲养员31 分钟前
React从前的SPA(CSR)到现在的SSR和SSG原理解析
前端·javascript·前端框架
不懂装懂的不懂32 分钟前
【 vue + js 】引入图片、base64 编译显示图片
前端·javascript·vue.js
搏博1 小时前
在WPS中通过JavaScript宏(JSA)调用DeepSeek官网API优化文档教程
javascript·人工智能·windows·深度学习·机器学习·wps
游戏开发爱好者82 小时前
使用克魔助手查看iOS 应用程序使用历史记录和耗能历史记录
websocket·网络协议·tcp/ip·http·网络安全·https·udp
BillKu2 小时前
el-input 中 select 方法使用报错:属性“select”在类型“HTMLElement”上不存在
前端·javascript·vue.js·elementui
涵信2 小时前
第一节:React 基础篇-React虚拟DOM原理及Diff算法优化策略
前端·javascript·react.js
碳烤小咸鱼3 小时前
蓝桥杯 Web 方向入门指南:从基础到实战
前端·javascript·css·蓝桥杯
inksci3 小时前
低代码控件开发平台:飞帆中粘贴富文本的控件
前端·javascript·低代码
不懂装懂的不懂3 小时前
【antd + vue】Tree 树形控件:默认展开所有树节点 、点击文字可以“选中/取消选中”节点
前端·javascript·vue.js
WEI_Gaot3 小时前
JS OBJECT 1 发展路线
前端·javascript