加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – 带有弹簧启动的’Access-Control-Allow-Origin’

发布时间:2020-12-15 01:40:02 所属栏目:大数据 来源:网络整理
导读:我有一个简单的spring启动服务,它运行在端口8080上暴露的docker容器中,该容器正在调用mysql数据库. 当我点击localhost:8080 / blogs时,我回来了[{“作者”:“Christopher Bolton”,“标题”:“测试标题1”,“内容”:“这是一些内容”,“日期”:“2017 -

我有一个简单的spring启动服务,它运行在端口8080上暴露的docker容器中,该容器正在调用mysql数据库.

当我点击localhost:8080 / blogs时,我回来了[{“作者”:“Christopher Bolton”,“标题”:“测试标题1”,“内容”:“这是一些内容”,“日期”:“2017 -08-29&; }]

当我直接在浏览器中点击它时,这工作得很好.但是,当我从jQuery尝试它时,我得到了正常的Access-Control-Allow-Origin.

这是我的春季启动服务:

@SpringBootApplication
@RestController
public class ChrisboltonServiceApplication {

public static void main(String[] args) {
    SpringApplication.run(ChrisboltonServiceApplication.class,args);
}

@Autowired
private JdbcTemplate jdbcTemplate;

@CrossOrigin
@RequestMapping(path="/blogs")
public @ResponseBody Iterable

这是我的jQuery:

$.ajax({
  url: "http://localhost:8080/blogs",crossDomain: true
}).done(function(data) {

  console.log(data);
});

但我仍然收到此错误:

XMLHttpRequest cannot load http://localhost:8080/blogs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

我已经通过将@CrossOrigin添加到getAllUsers()方法尝试了this,并且我在类级别尝试过.我也看了this,因为我在端口3000上运行我的UI.但是这个链接不是特定于Spring的.

编辑

添加我的请求标头:

GET /blogs HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept: */*
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) 
AppleWebKit/537.36 (KHTML,like Gecko) Chrome/60.0.3112.113 
Safari/537.36
Referer: http://localhost:3000/
Accept-Encoding: gzip,deflate,br
Accept-Language: en-US,en;q=0.8

网络标签中的响应(Chrome):

[{“author”:“Christopher Bolton”,“title”:“Test Title 1”,“content”:“这是一些内容”,“date”:“2017-08-29”}]

所以看起来我正在网络选项卡中获取数据.但是,我的console.log(data)生成了Access-Control-Allow-Origin

最佳答案
尝试将此添加到您的应用程序:

@SpringBootApplication
@RestController
public class ChrisboltonServiceApplication {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };
    }

...

另外,尝试从$.ajax()中删除crossDomain:true.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读