无法在服务器

时间:2015-11-10 15:26:45

标签: java ajax servlets

我正在尝试使用Ajax post请求在服务器上发送令牌。这是单独运行的基本html代码http://localhost:56471

$.ajax({
      type: 'POST',
      url: 'http://localhost:8080/sometoken' ,
      contentType: 'application/octet-stream; charset=utf-8',
      success: function(result) {
        // Handle or verify the server response.
          console.log("Result is: " + result);
      },
      processData: false,
      data: sometoken,
    });

我的servlet应用程序在端口8080上运行,试图获取令牌

public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException {
       String name=req.getParameter("token");
       response.setContentType("text/plain");
       response.setCharacterEncoding("UTF-8");
}

我对servlet完全不熟悉。这是我的第一个servlet。调用ajax帖子时遇到错误XMLHttpRequest cannot load http://localhost:8080/sometoken. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:56471' is therefore not allowed access.

任何人都可以帮我解决这个帖子请求如何没有错误吗?

由于

1 个答案:

答案 0 :(得分:0)

您的案例中的问题是着名的CORS(交叉原始资源共享)

  

跨域或跨域AJAX请求是来自Web的请求   在域X上托管的页面到域Y上托管的服务器。作为安全   预防措施浏览器禁止此操作,除非服务器说明了这一点   好吧,发送适当的Http-header(http://codepen.io/nicohaemhouts/post/cross-domain-ajax-with-tomcat-and-jquery)。

据我所知,由于您是两个域的所有者,因此您只需启用跨域交换信息即可克服此问题。这可以通过修改请求信息的服务器的默认行为来完成。

这可以通过修改web.xml并应用一个只允许这种交换的过滤器来完成:

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

假设您使用Tomcat,其他配置也可用。只需看看tomcats api