Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a simple spring boot service running in a docker container exposed on port 8080 that is calling a mysql database.

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"}]

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

Here is my spring boot service:

@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:

$.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 this by adding the @CrossOrigin to the getAllUsers() method and I have tried at the class level. I have also looked at this because I am running my UI on port 3000. But that link is not spring specific.

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):

[{"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

like image 669
Chris Bolton Avatar asked Sep 06 '17 00:09

Chris Bolton


2 Answers

JUST ADD DevConfiguration in any package then update application.properties file

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("*");
    }
}

Update application.properties file

# application.properties
spring.profiles.active=development
server.port=8090
like image 65
abhinavxeon Avatar answered Sep 20 '22 17:09

abhinavxeon


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: true from the $.ajax().

like image 35
acdcjunior Avatar answered Sep 21 '22 17:09

acdcjunior