无法在 JavaScript 中向 Java Web 服务(球衣)发出 CORS POST 请求?

Unable to make CORS POST request in javascript to java web service(jersey)?(无法在 JavaScript 中向 Java Web 服务(球衣)发出 CORS POST 请求?)

本文介绍了无法在 JavaScript 中向 Java Web 服务(球衣)发出 CORS POST 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jersey 在 Java Web 服务中实现跨资源源共享.我创建的资源如下:

I am implementing Cross Resource Origin Sharing in Java Web services using Jersey.I created resource as followes:

@POST
    @Path("/getSubjects")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response getSubjects(TokenCheck tc) throws IOException, ServletException{ 
        String token = tc.getToken();
        String result = "";
        if(!token.equals("") && !token.equals(null)){
            context.getRequestDispatcher("/GetSubjectsWs?token="+token).include(request, response);
            String subs = request.getAttribute("subjects").toString();
            result = "{"subjects":""+subs+""}";
        }else {
            result = "{"subjects":"['Invalid Token login again']"}";
        }
        JSONObject j = null;
        try {
            j = new JSONObject(result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return Response.status(200).entity(j).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "POST, GET, OPTIONS").header("Access-Control-Allow-Headers", "Content-Type:application/json").build(); 
    }

并使用 javascript 作为发布请求:

and making post request using javascript as :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Client</title>
<script type="text/javascript">
function restReq() {
    var url = "http://localhost:8888/WebservicesServer/restful/getserver/getSubjects";
    var json = {
            "token":"8495C211F11C9B18E6651E03EB2995BC"
    };
    var client = new XMLHttpRequest();
    client.open("POST", url, true);
    client.setRequestHeader("Access-Control-Request-Methods", "POST");
    client.setRequestHeader("Content-Type", "application/json");
    client.send(json);
    client.onreadystatechange = function() {
        if (client.readyState == 4) {
           if ( client.status == 200) 
               console.log("success: " + client.responseText);
          else
              console.log("error: " +client.status+" "+ client.responseText);
       }
 };
}
</script>
</head>
<body>
<input type="button" value="getSubjects" onclick="restReq();">
</body>
</html>

当我单击 chrome 中的 getSubjects 按钮时,我收到 错误:XMLHttpRequest 无法加载 ..localhost:8888/WebservicesServer/restful/getserver/getSubjects.Access-Control-Allow-Origin 不允许 Origin null.但我可以通过 GET 请求得到响应,问题在于 POST 请求我的浏览器 url file:///E:/​​Documents%20and%20Settings/Srinivas/Desktop/wars/JSClient2.html(文件系统)我尝试了很多方法,比如设置原点等,仍然无法得到 json 响应(服务器是 Tomcat 7)请帮助解决这个问题.

When i clicked getSubjects Button in chrome I am getting error as : XMLHttpRequest cannot load ..localhost:8888/WebservicesServer/restful/getserver/getSubjects. Origin null is not allowed by Access-Control-Allow-Origin. But i am able to get response with GET request,problem is with POST request my browser url file:///E:/Documents%20and%20Settings/Srinivas/Desktop/wars/JSClient2.html (File system) I tried in many ways like by setting origin etc, still unable to get json response (Server is Tomcat 7) please help to overcome this problem.

推荐答案

如果你正在使用 CORS,那么你应该将它作为一个过滤器来实现,而不是试图将它嵌入到每个资源的每个方法中.这是一个简单的示例(如果您担心,您可能需要调整设置以限制它):

If you are using CORS then you should implement it as a filter rather than attempt to embed it in every method of every resource. Here's a simple example (you might want to tweak the settings to restrict it if that's of concern to you):

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

/**
 * Filter to handle cross-origin resource sharing.
 */
public class CORSFilter implements ContainerResponseFilter
{
  private static final String ORIGINHEADER = "Origin";
  private static final String ACAOHEADER = "Access-Control-Allow-Origin";
  private static final String ACRHHEADER = "Access-Control-Request-Headers";
  private static final String ACAHHEADER = "Access-Control-Allow-Headers";

  public CORSFilter()
  {
  }

  @Override
  public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response)
  {
    final String requestOrigin = request.getHeaderValue(ORIGINHEADER);
    response.getHttpHeaders().add(ACAOHEADER, requestOrigin);

    final String requestHeaders = request.getHeaderValue(ACRHHEADER);
    response.getHttpHeaders().add(ACAHHEADER, requestHeaders);
    return response;
  }
}

这篇关于无法在 JavaScript 中向 Java Web 服务(球衣)发出 CORS POST 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无法在 JavaScript 中向 Java Web 服务(球衣)发出 CORS POST 请求?

基础教程推荐