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

相关推荐
Revolution6112 分钟前
一段 JavaScript 代码执行时,到底发生了什么
前端·javascript
To_OC9 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
To_OC11 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn11 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
এ慕ོ冬℘゜12 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
随心点儿13 小时前
js postMessage 实现跨域发送消息-应用示例
javascript·ecmascript·postmessage
kyriewen14 小时前
我让AI改一个bug——它偷偷动了5个我没让它碰的地方
前端·javascript·ai编程
gis开发之家18 小时前
《Vue3 从入门到大神35篇》Vue3 源码详解(五):effect 依赖收集原理——track 与 trigger 是如何工作的?
javascript·typescript·前端框架·vue3·vue3源码
橘子星20 小时前
我一个前端切图仔,凭什么能在浏览器里跑大模型?
前端·javascript·前端框架
半个落月20 小时前
用 LangChain JS 做可控写作实验:理解温度参数、提示词与异步调用
javascript·人工智能·后端