ajax跨域请求SpringBoot

本文介绍了一种在SpringBoot项目中解决跨域问题的方法,通过配置支持跨域请求的Configuration类实现。同时展示了HTTP请求接口及前端请求页面的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    跨域,就是从不同的的IP端口获取数据,比如说,从www.baidu.com获取数据,就叫跨域!那么localhost:8080与localhost:8081之间呢?也叫跨域。如果处理的不好,就会报错,不仅前端报错,后端也会报错。

    那么在SpringBoot中如何解决跨域问题,如下:

1、编写一个支持跨域请求的 Configuration

package com.wangru.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * 处理AJAX请求跨域的问题
 * @author wangru
 * @time 2018-07-13
 */
@Configuration
public class CrossDomain extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                .allowCredentials(false).maxAge(3600);
    }
}

2、http请求接口

package com.wangru.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloWorldController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World ! Hello SpringBoot !";
    }

    @RequestMapping(value = "/data", method = RequestMethod.GET)
    @ResponseBody
    public String data() {
        return "This is My data ! ";
    }
}

3、前端请求页面

<!DOCTYPE html>
<head>
    <meta charset="gbk">
    <title>springBoot</title>
</head>
<body>

    <div id="main" style="height:600px"></div>
	

	<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
    <script type="text/javascript">
      $.ajax({
	  
			async : false ,
			type : "get",
			url:"http://192.168.1.102:8081/hello",
			data : {
					
				},
			dataType : "jsoup",
			
			success:function(result){
				alert(result);
			}
		});

		
    </script>
</body>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值