【问题标题】:Setting up a REST API with CORS on Eclipse Tomcat 6在 Eclipse Tomcat 6 上使用 CORS 设置 REST API
【发布时间】:2017-07-13 19:00:49
【问题描述】:

我正在尝试做的事情:

I want to set up a server that processes GET requests and can be called from any domain.
None of the data is private so I want to enable CORS.

为什么?

I'm trying to teach people web development one step at a time.
Step 1 I want to teach people basic javascript and pulling data without them
needing to interact with the server side at all.

当前的基础设施:

I'm running a tomcat server in eclipse, with a few get requests coded in java.
I want users to be able to make get requests from their localhosts or 
from any url just by typing in the chrome console. I currently can execute the
get requests from the same domain, but when I try from my localhost I get an error.

到目前为止我已经尝试过:

oh boy where to start:
1. upgrading tomcat, possible but would need to go through lots of bureaucracy
2. Updating the web.xml with a CORS filter. 
   Every time I do this it ends up failing to start the server
3. jsonp. This works to get the data looking in the network tab, but my success
   function isn't being called, and research shows it's because I'm passing
   a json object and the browser is expecting a jsonp. How can I do that from the
   server?
4. Setting crossOrigin: true in the ajax request. That doesn't work and I still
   get the same "no Access-control-allow-origin header is present..." error.

关于其他尝试的任何建议,或者关于为什么我尝试过的方法都没有奏效的详细信息?

谢谢。

【问题讨论】:

  • 呃,我以为我很聪明地使用代码缩进并使它看起来更好,但是突出显示很糟糕:(

标签: javascript tomcat server cors


【解决方案1】:

好吧,您所描述的场景所需要的只是“Access-control-allow-origin”标头,因为错误试图告诉您。到目前为止,您尝试的所有步骤似乎都没有朝着那个方向发展(尽管可能使用了 CORS 过滤器)。

当然有更优雅的方式来添加 CORS 标头,但我认为您可以通过在 servlet 中添加标头来避免:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setHeader("Access-Control-Allow-Origin", "*");
}

【讨论】:

  • 这可能是一个愚蠢的问题,但是 servlet 是什么?作为参考,这是我现在设置请求的方式: @RequestMapping(value = "/blah",method=RequestMethod.GET) @ResponseBody [java method] 那是 servlet 吗?我将 doGet 函数添加到同一个类中,但什么也没做,我需要更改的 tomcat 配置文件之一中有什么东西吗?谢谢。
  • 没有愚蠢的问题 :-) 也许你可以告诉我你是如何在 Java 中生成响应的,因为这是你需要设置标头而不是请求的地方。
  • 啊,春天。看看这个:docs.spring.io/spring/docs/current/spring-framework-reference/… 似乎添加 @CrossOrigin 可能是您正在寻找的。​​span>
  • CrossOrigin 看起来正是我想要的。不幸的是,当我输入@CrossOrigin 时,我收到错误“CrossOrigin 无法解析为一种类型”,尽管服务器仍将运行,但在尝试发出该 GET 请求时我仍然收到 CORS 错误。对于其他解决方案,我不确定应该在哪里定义扩展 WebMvcConfigurerAdapter 的类,以便 tomcat 服务器将其添加回响应标头中。
  • 您是否添加了导入?导入 org.springframework.web.bind.annotation.CrossOrigin
猜你喜欢
  • 2017-02-26
  • 2016-08-26
  • 1970-01-01
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
相关资源
最近更新 更多