2017-09-06 35 views
1

我有一個簡單的服務,運行在端口8080上的docker容器中,該端口調用mysql數據庫。'Access-Control-Allow-Origin'with spring boot

當我打localhost:8080/blogs,我回來[{"author":"Christopher Bolton","title":"Test Title 1","content":"This is some content","date":"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<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. 

我已經試過this@CrossOrigin添加到getAllUsers()方法我已經在課堂上嘗試過了。我也看過this,因爲我正在運行我的端口3000上的用戶界面。但那個鏈接不是特定於春天的。

編輯

添加我的請求頭:

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":"This is some content","date":"2017-08-29"}]

所以看起來我得到的數據回到網絡標籤。然而,我console.log(data)產生Access-Control-Allow-Origin

回答

3

嘗試添加以下內容到應用程序:

@SpringBootApplication 
@RestController 
public class ChrisboltonServiceApplication { 

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

... 

此外,嘗試從$.ajax()取出crossDomain: true

+0

我仍然保留'@ CrossOrigin'嗎?仍然有相同的錯誤。 –

+0

另外,我在上面添加了使用docker並暴露端口8080的事實。也許這可能是問題的一部分? –

+0

其實,所有的東西都應該一直和'@ CrossOrigin'一起工作。我剛剛在這裏測試,它工作正常。您使用碼頭集裝箱的事實應該會影響它。你的容器基於什麼形象?在容器內部的彈簧靴前沒有某種代理嗎? – acdcjunior

0

如果您希望:8080允許請求,您可以將@CrossOrigin("http://localhost:8080")添加到正確的方法。這是一個端點/控制器的簡單配置。當然,您也可以在那裏使用變量進行自定義。