繁体   English   中英

在Eclipse Tomcat 6上使用CORS设置REST API

[英]Setting up a REST API with CORS on Eclipse Tomcat 6

我正在尝试做的是:

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.

关于尝试其他事情的任何建议,或者可能是为什么我尝试过的所有事情都没有奏效的细节?

谢谢。

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

当然,添加CORS标头的方式更优雅,但我认为您可以通过在Servlet中添加标头来摆脱困境:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM