'访问控制允许来源'标头不存在于请求的资源上

时间:2017-08-09 12:05:25

标签: javascript java ajax jax-rs

如何调试此问题?

这是我的java代码。我通过设置Access-Control-Allow-Origin给予所有ip的许可,但它仍然没有" Access-Control-Allow-Origin"

   return Response.ok().entity(jsonNodeToSend.toString()).header("Access-Control-Allow-Origin", "*").build();

这是我的javascript代码。

var dict = {
"clientMac" : "48:43:7c:53:53:d1",
"BSSID" : ""
};

$.ajax({
type: 'POST',
url: 'http://104.155.189.170:8080/Localization/rest/clientMacPosition/get/7',
crossDomain: true,
contentType: "application/json; charset=UTF-8",
data: dict,
dataType: 'json',
beforeSend: function(xhr) {
    xhr.setRequestHeader('MessageId', 'abc123');
},
success: function(responseData, textStatus, messageId) {
    console.log("success");
},
error: function(responseData, textStatus, errorThrown) {
    console.log(textStatus);
    console.log(responseData);
    console.log(errorThrown);
}

});

这是我的方法,它获取数据并响应请求。

@Path("/get/{customerProjectId}")
@POST
@Produces({ MediaType.APPLICATION_JSON })
public Response gettingRecentPosition(LocationAPIReceiverDTO locationAPIReceiverDTO,
                                      @PathParam("customerProjectId") int customerProjectId) {

     JsonNode jsonNodeToSend = null;


    return Response.ok().entity(jsonNodeToSend.toString()).header("Access-Control-Allow-Origin", "*").build();


}

网址:http://104.155.189.170:8080/Localization/rest/clientMacPosition/get/7

jsonData:{     " clientMac" :" 48:43:7c:53:53:d1",     " BSSID" :" 33:" }

我在POST人员中的REST调用响应。

enter image description here

2 个答案:

答案 0 :(得分:1)

请为您的应用程序创建一个过滤器,并添加以下标题以修复CORS问题:

public class ApplicationFilter实现Filter {

 @Override
 public void destroy() {
     // TODO Auto-generated method stub

 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
 throws IOException, ServletException {

     HttpServletRequest httpRequest = (HttpServletRequest) request;
     HttpServletResponse httpResponse = (HttpServletResponse) response;
     httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
     httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
     httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
     httpResponse.setHeader("Access-Control-Max-Age", "3600");
     httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization, Content-Type,*");
     if (httpRequest.getMethod().equals("OPTIONS")) {
         httpResponse.setStatus(HttpServletResponse.SC_OK);
         return;
     }
     chain.doFilter(httpRequest, httpResponse);
 }


 @Override
 public void init(FilterConfig arg0) throws ServletException {
     // TODO Auto-generated method stub

 }

}

答案 1 :(得分:0)

您是否尝试在控制器方法上添加@CrossOrigin注释?

以下是如何使用spring设置交叉原点的示例:https://spring.io/guides/gs/rest-service-cors/