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

  • 13
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值