当从我的 tomcat 网络服务发送一个 post 请求时,我收到如下错误: “对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问“null”来源。“
我正在使用 tomcat 9.* 并使用 jax-rs java web api 开发我的 web 服务。
虽然我已经用 postman 测试了我的网络服务,但我的网络服务得到了很好的响应(http 200 响应)。然而,当我尝试发送 ajax post 请求时,我收到了上面的消息。我尝试启用 CORS 过滤器并尝试发送工作正常的获取请求..
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 函数:
@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 请求。”
您的意思是 GET 方法有效但 POST 方法无效?如果是这样,您必须在您的 REST 服务/终端以及这些设置上允许它 header (“访问控制允许来源”,“*”) header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
最后,如果您的 AJAX 仍然返回失败的尝试
$.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));
}'
关于jquery - 来自 jax-rs 网络服务的 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074831/