java 带有弹簧靴的“Access-Control-Allow-Origin”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46065156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:02:25  来源:igfitidea点击:

'Access-Control-Allow-Origin' with spring boot

javaspringspring-bootcors

提问by Chris Bolton

I have a simple spring bootservice running in a dockercontainer exposed on port 8080that is calling a mysqldatabase.

spring boot在调用数据库的docker端口8080上公开的容器中运行了一个简单的服务mysql

When I hit localhost:8080/blogs, I get back [{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"2017-08-29"}]

当我击中时localhost:8080/blogs,我回来了[{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"2017-08-29"}]

This is working just fine when I hit it directly in the browser. However, when I try it from jQueryI am getting the normal Access-Control-Allow-Origin.

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

Here is my spring boot service:

这是我的 Spring Boot 服务:

@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<ChrisBolton> getAllUsers() {
    List<ChrisBolton> result = jdbcTemplate.query(
            "SELECT * FROM blog",
            (rs, rowNum) -> new ChrisBolton(rs.getString("author"), 
                                               rs.getString("title"), 
                                               rs.getString("content"), 
                                               rs.getDate("date"))
    );

    return result;
}
}

Here is my jQuery:

这是我的jQuery

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

  console.log(data);
});

But I am still getting this error:

但我仍然收到此错误:

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.

I have tried thisby adding the @CrossOriginto the getAllUsers()method and I have tried at the class level. I have also looked at thisbecause I am running my UI on port 3000. But that link is not spring specific.

我已经通过在方法中添加来尝试这个,并且我已经在类级别尝试过。我也看过这个,因为我在 port 上运行我的 UI 。但该链接不是特定于 spring 的。@CrossOrigingetAllUsers()3000

EDIT

编辑

Adding my request headers:

添加我的请求标头:

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

Response in network tab (Chrome):

网络选项卡(Chrome)中的响应:

[{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"2017-08-29"}]

[{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"2017-08-29"}]

So it looks like I am getting data back in the network tab. However, my console.log(data)produces the Access-Control-Allow-Origin

所以看起来我正在网络选项卡中取回数据。然而,我console.log(data)生产的Access-Control-Allow-Origin

回答by acdcjunior

Try adding this to your application:

尝试将其添加到您的应用程序中:

@SpringBootApplication
@RestController
public class ChrisboltonServiceApplication {

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

...

Also, try removing the crossDomain: truefrom the $.ajax().

另外,尝试crossDomain: true$.ajax().

回答by Artur Czopek

You can add @CrossOrigin("http://localhost:8080")to proper method if you want :8080to allow request there. It's a simple config for one endpoint/controller. You can use variable there too for customization later of course.

@CrossOrigin("http://localhost:8080")如果您想:8080在那里允许请求,您可以添加到适当的方法。这是一个端点/控制器的简单配置。当然,您也可以在那里使用变量进行自定义。