springboot 前后台分离ajax跨域解决

一.创建springboot项目
1.配置application.yml

server:
  port: 8091

2 . 第一种解决跨域问题是利用@Configuration配置跨域。
2.1在新建conf包中创建跨域配置类CorsConfig


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 CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址,所有访问地址

        //如果不使用”*”(即允许全部访问源),则可以配置多条访问源来做控制。
//        corsConfiguration.addAllowedOrigin("http://localhost:8082/");
//        corsConfiguration.addAllowedOrigin("http://test.aimaonline.cn/");


        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

3 .正在新建controller包下创建一个userController

@Controller
public class userController {
	@GetMapping("/hello1")
    @ResponseBody
    public String hello1(){
        return "hello1";
   		 }
    @PostMapping("/hello2")
    @ResponseBody
    public String hello2(String username,int password){
        return username;
   		 }
    }

4.第二种比较简单,就是在上面userController加上@CrossOrigin就能实现跨域
在这里插入图片描述
二.新建一个前端界面
1.在idea中新建空白文件夹,拖入所需文件,目录如下:
在这里插入图片描述
2 .在test.html写ajax请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>跨域test</title>
</head>
<body>
<button id="btn">按钮1</button>
<button id="btn2">按钮2</button>
<div id="app"></div>

<script src="js/jquery-3.2.1.js"></script>
<script>

    $(function () {
        $("#btn").on("click",function () {
            $.get('http://localhost:8091/hello1', function (msg) {
                $("#app").html(msg);
            });
        })

        $("#btn2").on("click",function () {
            $.post(
                'http://localhost:8091/hello2',
                {username:"haha",password:123456},
                function (msg) {
                $("#app").html(msg);
        });
    })
    })
    
</script>
</body>
</html>

最后实现效果:

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值