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,或者浏览器的同源策略有什么其他的隐形附加条件(已迷茫)

相关推荐
进击的尘埃9 分钟前
基于 LangChain.js 的前端 Agent 工作流编排:Tool 注册、思维链可视化与多步推理的实时 DAG 渲染
javascript
颜酱35 分钟前
最小生成树(MST)核心原理 + Kruskal & Prim 算法
javascript·后端·算法
蜡台1 小时前
Node 版本管理器NVM 安装配置和使用
前端·javascript·vue.js·node·nvm
奶昔不会射手2 小时前
自定义vue3函数式弹窗
前端·javascript·css
wuhen_n3 小时前
破冰——建立我们的AI开发实验环境
前端·javascript
牛奶3 小时前
HTTP裸奔,HTTPS穿盔甲——它们有什么区别?
前端·http·https
张元清4 小时前
React Hooks vs Vue Composables:2026 年全面对比
前端·javascript·面试
yuki_uix4 小时前
从三个自定义 Hook 看 React 状态管理的设计思想
前端·javascript
CyrusCJA4 小时前
JavaScript原型与super关键字
前端·javascript·js
吠品4 小时前
提升效率:掌握Git Cherry-Pick,精准管理PR提交!
网络协议·https·ssl