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

相关推荐
xiaoxue..1 小时前
合并两个升序链表 与 合并k个升序链表
java·javascript·数据结构·链表·面试
要加油哦~2 小时前
AI | 实践教程 - ScreenCoder | 多agents前端代码生成
前端·javascript·人工智能
一个public的class2 小时前
你在浏览器输入一个网址,到底发生了什么?
java·开发语言·javascript
青茶3602 小时前
php怎么实现订单接口状态轮询请求
前端·javascript·php
火车叼位2 小时前
脚本伪装:让 Python 与 Node.js 像原生 Shell 命令一样运行
运维·javascript·python
VT.馒头2 小时前
【力扣】2727. 判断对象是否为空
javascript·数据结构·算法·leetcode·职场和发展
鱼毓屿御3 小时前
如何给用户添加权限
前端·javascript·vue.js
JustHappy3 小时前
「web extensions🛠️」有关浏览器扩展,开发前你需要知道一些......
前端·javascript·开源
xixixin_3 小时前
【JavaScript 】从 || 到??:JavaScript 空值处理的最佳实践升级
开发语言·javascript·ecmascript
belldeep3 小时前
python:用 Flask 3 , mistune 2 和 mermaid.min.js 10.9 来实现 Markdown 中 mermaid 图表的渲染
javascript·python·flask