Ajax request from jax-rs web service

人走茶凉 提交于 2020-11-30 00:28:28

问题


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."

I'm using tomcat 9.* and developed my web service with jax-rs java web api.

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..

the 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>'

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();
    }  

the ajax request:

    $.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)); 
    }'

回答1:


You say "I tried to enable the CORS filter and tried to send get request that working fine."

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")

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)); 
    }'


来源:https://stackoverflow.com/questions/50074831/ajax-request-from-jax-rs-web-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!