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

时间:2017-07-13 19:00:50

标签: javascript tomcat server cors

我正在尝试做什么:

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.

有关其他事情的任何建议,或者可能详细说明为什么我尝试过的事情都没有用过?

感谢。

1 个答案:

答案 0 :(得分:0)

好吧,您所描述的方案所需的只是“Access-control-allow-origin”标题,正如错误试图告诉您的那样。到目前为止,您尝试的所有步骤似乎都没有进入该方向(尽管可能使用CORS过滤器)。

当然有更优雅的方法来添加CORS标头,但我认为你可以通过在servlet中添加标头来逃脱:

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