我正在调用部署在另一台tomcat服务器上的webservice。我收到以下错误:
未捕获的ReferenceError:未定义$ http index.html:1 XMLHttpRequest无法加载http://192.168.200.85:8080/Test/webapi/GetCustomerProfile?accountNo=81701。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点'null'访问。
以下是我的网络服务代码:
import com.ef.wrapupcodes.Skills.ServiceData;
package com.ef.wrapupcodes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.ef.wrapupcodes.Skills.ServiceData;
@Path("/services/{serviceName}")
public class GetSG
{
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response GetSkillGroups(@PathParam ("serviceName") String serName)
{
Skills services = new Skills(serName);
ServiceData list = services.getServices();
final GenericEntity<ServiceData> outPut =
new GenericEntity<ServiceData> (list) { };
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, OPTIONS")
.status(200).entity(outPut).build();
}
}
有人可以帮我解决这个问题吗?
答案 0 :(得分:2)
添加以下代码:
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With").build();
另一个解决方案(创建类实现ContainerResponseFilter)
@Override
public ContainerResponse filter(ContainerRequest creq, ContainerResponse cresp) {
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
return cresp;
}
<servlet>
<servlet-name>CORS Filter</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>your.package.CORSFilter</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CORS Filter</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>