【问题标题】:How to set Access-Control-Allow-Origin when using @RestController?使用@RestController时如何设置Access-Control-Allow-Origin?
【发布时间】:2019-02-15 20:45:37
【问题描述】:

我正在使用 @RestController 来提供 REST 服务。但我需要在响应头中设置 Access-Control-Allow-Origin。我该怎么做?

我的 RestController:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class restController  {

   @RequestMapping("/some")
   public Response some(@RequestParam(value="body")  String user) {
      return new Response(user);
   }
}

我的回应:

public class Response {

  long id;
  String user;

  public Response(String user) {
       this.id = 7;
       this.user = user;
  }
}

@RestController 工作得很好,但是如何修改它或设置 Access-Control-Allow-Origin 的响应?

【问题讨论】:

标签: java spring http header response


【解决方案1】:

试试这个代码:

  @CrossOrigin(origins = "*")
   @RequestMapping("/some")
   public Response some(@RequestParam(value="body")  String user) {
      return new Response(user);
   }

或者这个

@RequestMapping("/some")
public Response some(@RequestParam(value="body")  String user,HttpServletResponse 
response) {
   response.addHeader("Access-Control-Allow-Origin", "*");
   return new Response(user);
}

【讨论】:

  • 非常感谢您的回复!有没有办法在浏览器中看到这种变化?比如在firefox的web开发者控制台中?
  • 您可以在任何浏览器开发工具网络部分看到类似 CORS 的响应标头..
  • 我尝试了上述两个建议,但在 Firefox 的网络部分没有看到类似 CORS 响应的任何内容
  • 我的响应标头只有以下内容:HTTP/1.1 200 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Tue, 11 Sep 2018 12:08:18格林威治标准时间
  • 好的,现在我看到了:HTTP/1.1 200 Access-Control-Allow-Origin: * Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Tue, 11格林威治标准时间 2018 年 9 月 13:10:57
猜你喜欢
  • 1970-01-01
  • 2015-10-29
  • 2014-06-09
  • 2017-06-15
  • 1970-01-01
  • 2021-01-01
  • 2017-07-31
  • 2016-07-21
  • 1970-01-01
相关资源
最近更新 更多