SpringBoot2.0(一):配置跨域请求

本文介绍如何在SpringBoot项目中使用@Configuration注解配置跨域请求,通过自定义CORS配置,实现对/api/**路径的跨域访问。并提供了一个ApiController示例,展示如何返回包含名字和密码的数据。同时,通过在两个不同端口运行的项目进行测试,验证跨域配置的有效性。

利用@Configuration配置跨域请求


代码实现如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * CORS配置
 * @author xiaofei
 * @create 2019-07-26 下午 04:24
 */
@Configuration
public class CustomCorsConfig extends WebMvcConfigurationSupport {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**");
    }
}

写一个ApiControll:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * api接口
 *
 * @author xiaofei
 */

@RestController
@RequestMapping("/api/")
public class ApiController {

    @RequestMapping("get")
    public HashMap<String, Object> get(@RequestParam String name) {
        HashMap<String, Object> map = new HashMap();
        map.put("name", name);
        map.put("pwd", 123456);
        return map;
    }
}

在application.properties中配置:

server.port=8080

然后访问:http://localhost:8080/api/get?name=xiaofei 测试

{"name":"xiaofei","pwd":123456}

在创建另一个项目测试
application.properties中配置:

server.port=8081

新建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试CORS</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>
<body>
<button id="btu" >按钮</button>
    <script>
        $("#btu").click(function () {
           $.post(
               // 请求路径
               "http://localhost:8080/api/get?name=xiaofei",
               function (map) {
                   console.log(map);
               }

           );
        });
    </script>
</body>
</html>

访问:

server.port=8081

测试结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小飞技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值