本文主要是介绍springbootajaxhas been blocked by CORS policy: No ‘Access-Control-Allow-Origin,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。
ajax+springboot解决跨域问题,以下报的错误就是html跨域的问题
Access to XMLHttpRequest at 'http://localhost:8080/user/login1' from origin 'http://localhost:59033' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
springboot解决跨域的问题的两种方法
前端测试代码:
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title></title>
</head><body>
<div id="form-div"><form id="form1"><p>用户名:<input name="email" type="text" id="txtUserName" tabindex="1" size="15" value="" /></p><p>密 码:<input name="password" type="text" id="TextBox2" tabindex="2" size="16" value="" /></p><p><input type="button" value="登录" onclick="login()"> <input type="reset" value="重置"></p></form>
</div>
</body>
<script type="text/javascript" src="../static/jquery/jquery-3.3.1.js"></script>
<script type="text/javascript">function login() {$.ajax({//几个参数需要注意一下type: "POST", //方法类型dataType: "json", //预期服务器返回的数据类型url: "http://localhost:8080/user/login1", //urldata: $('#form1').serialize(),success: function(result) {console.log(result); //打印服务端返回的数据(调试用)if(200 == result.resultCode) {alert("SUCCESS");};},error: function() {alert("异常!");}});}
</script></html>
第一种:写一个class,配置的class
package com.example.demo;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;/*** Author:Yangjingcheng* Date:2018/*/
@Configuration
public class CorsConfig {private CorsConfiguration buildConfig() {CorsConfiguration corsConfiguration = new CorsConfiguration();corsConfiguration.addAllowedOrigin("*");corsConfiguration.addAllowedHeader("*");corsConfiguration.addAllowedMethod("*");return corsConfiguration;}@Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();// 配置所有请求source.registerCorsConfiguration("/**", buildConfig());return new CorsFilter(source);}
}
第二种,在你要访问的Controller的方法上面加上注解 @CrossOrigin
package com.example.demo;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;@Controller
public class TestController {@CrossOrigin@RequestMapping("/user/login1")@ResponseBodypublic List<User> userLogin(User user) {System.out.println(user);ArrayList<User> users = new ArrayList<>();for (int i = 0; i < 3; i++) {users.add(user);}return users;}
}
OK了
转自:https://blog.csdn.net/lovePaul77/article/details/85681404
这篇关于springbootajaxhas been blocked by CORS policy: No ‘Access-Control-Allow-Origin的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!