来自jax-rs Web服务的Ajax请求 [英] Ajax request from jax-rs web service
问题描述
从我的tomcat Web服务发送发帖请求时,出现以下错误: 对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头.因此,不允许访问源'null'."
While sending a post request from my tomcat web service i got an error as below: " Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
我正在使用tomcat 9. *,并使用jax-rs Java Web api开发了我的Web服务.
I'm using tomcat 9.* and developed my web service with jax-rs java web api.
虽然我已经用邮递员测试了我的Web服务,但是我的Web服务获得了很好的响应(http 200响应).但是,当我尝试发送ajax发布请求时,我收到了上面的消息.我试图启用CORS筛选器,并尝试发送可以正常工作的get请求.
While i have tested my web service with postman, i got a good response from my web service (http 200 response). Yet, when i tried to send ajax post request i got the message above. I tried to enable the CORS filter and tried to send get request that working fine..
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>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>'
jax-rs post函数:
the jax-rs post function:
@POST
@Path("/users2")
@Consumes("application/json")
@Produces(MediaType.APPLICATION_JSON)
public Response SetAllTlcsStatus(List<TrafficLight> c){
System.out.println("You have entered the SetTlc function");
return Response.ok() //200
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE,
PUT")
.allow("OPTIONS").build();
}
ajax请求:
$.ajax({
type : "POST",
url : "http://localhost:8080/userManagement/rest/Traffic/users2",
contentType :"application/json; charSet=UTF-8",
data : d,
dataType : "json",
beforeSend: function (xhr){
console.log('Before');
xhr.setRequestHeader('Authorization', make_base_auth(user, pass));
}'
推荐答案
您说:我尝试启用CORS过滤器,并尝试发送 get 正常工作的请求."
You say "I tried to enable the CORS filter and tried to send get request that working fine."
您是说GET方法有效但POST无效吗?如果是这样,则必须在REST服务/终端以及这些设置上允许它 标头("Access-Control-Allow-Origin","*") 标头("Access-Control-Allow-Methods","GET,POST,DELETE,PUT")
Do you mean that GET method works but POST not? If so you must allow it on your REST service/terminal and also these settings header("Access-Control-Allow-Origin", "*") header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
最后,如果您的AJAX仍然有返回失败的尝试,请尝试
Finally, if by any chance your AJAX still returns failed try
$.ajax({
type : "POST",
url : "http://localhost:8080/userManagement/rest/Traffic/users2",
contentType :"application/json; charSet=UTF-8",
data : d,
dataType : "json",
**xhrFields: {
withCredentials: true
},
crossDomain: true,**
beforeSend: function (xhr){
console.log('Before');
xhr.setRequestHeader('Authorization', make_base_auth(user, pass));
}'
这篇关于来自jax-rs Web服务的Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!