关键词搜索

源码搜索 ×
×

访问spring boot项目提供的web api提示跨域问题

发布2019-03-28浏览766次

详情内容

天杀的,没天理啊!本机的api,居然提示跨域!

如前两篇文章
spring boot web api
spring boot里面对WEB API的单元测试
所述的api,看上去头头是道,但我在前端用js刚开始测试的时候,却提示跨域。

前端代码如下:

var url1 = "http://localhost:8085/api/authors/kv/1?t=2";
var data1 = "name=chenqu&desc=foolish";
var ctype1 = "application/x-www-form-urlencoded;charset=utf-8";

var url2 = "http://localhost:8085/api/authors/json/1?t=2";
var data2 = JSON.stringify({
	"name":"chenqu",
	"desc":"foolish"
});
var ctype2 = "application/json; charset=utf-8";

$.ajax({
	url: url2,
	data: data2,
	contentType: ctype2,		
	//dataType: "json",
	type: "POST",
	success: function (data) {
		alert(data);
	},
	error: function (rq, status, thrown) {
		alert(rq.responseText + "," + status + ": " + thrown);
	}
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

就本文涉及的案例,唯有在服务器端修改一下。从网上抄来一个例子,将代码加进去就可以了:

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

@Configuration
public class WebConfig {

    /**
     * 跨域请求支持
     */
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*")
                        .allowedMethods("*").allowedHeaders("*")
                        .allowCredentials(true)
                        .exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L);
            }
        };
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

也无须调用。应该是头部有个注解:@Configuration,自动生效了吧。

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载