提问者:小点点

带Spring启动的“访问控制允许来源”


我有一个简单的< code>spring boot服务,运行在端口< code>8080上的< code>docker容器中,该容器调用< code>mysql数据库。

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

当我在浏览器中直接点击它时,它工作得很好。然而,当我从< code>jQuery中尝试时,我得到了正常的< code > Access-Control-Allow-Origin 。

这是我的Spring靴服务:

@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;
}
}

这是我的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(),并在类级别进行了尝试。我还研究了这一点,因为我正在端口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):

[{"作者":"克里斯多夫·博尔顿","标题":"测试标题1","内容":"这是一些内容","日期":"2017-08-29"}]

因此,看起来我正在网络选项卡中获取数据。然而,我的控制台。日志(数据)生成访问控制允许原点


共3个答案

匿名用户

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

@SpringBootApplication
@RestController
public class ChrisboltonServiceApplication {

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

...

此外,尝试从< code>$中删除< code>crossDomain: true。ajax()。

匿名用户

只需在任何包中添加DevConfiguration,然后更新应用程序。属性文件

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@Profile("development")
public class DevConfiguration implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS").allowedOrigins("*");
    }
}

更新application.properties文件

# application.properties
spring.profiles.active=development
server.port=8090

匿名用户

如果您希望:8080允许请求,则可以将@CrossOrigin(“http://localhost:8080”)添加到正确的方法中。这是一个endpoint/控制器的简单配置。当然,您也可以在那里使用变量进行自定义。