Buddhika Alwis
Buddhika Alwis

Reputation: 371

How to send application/json jQuery ajax request in jaxrs without having ‘Access-Control-Allow-Origin’ missing error

My problem is when I am sending a request to a jaxrs api server from browser it is failing from preflight request saying

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:9091/api/employee/add. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I don't understand why I couldn't make the preflight request success. My postman request was successful. But when sending the request from browser it is falling.

Ajax request:

              $.ajax({


                type: "POST",
                url: "https://localhost:9091/api/employee/add",
                cache: false,
                data:JSON.stringify(employeeJSONObj),
                dataType: "json",
                contentType: 'application/json',

                success: function(response){


                });

Json payload:

{   
    "employeeName":"Name3",
    "nRIC":"NRIC3",
    "dateOfBirth":"2017-01-02",
    "address":"Address",
    "salaryMode":"Monthly",
    "bankAccount":"Bank Account",
    "appointmentAs":"Security Supervisor (SS)",
    "nationality":"Malaysian",
    "maritalStatus":"Married",
    "sex":"Female",
    "nextOfKin":"Next Of kin",
    "mobilePhone":"Mobile Phone",
    "profilePicture":null,
    "document":null
}

Jersy jaxrs API server integration:

@POST
    @Consumes({ MediaType.APPLICATION_JSON})
    @Produces({ MediaType.APPLICATION_JSON})
    @Path("add")
    public Response addEmployee(Employee employee) {

        EmployeeImpl employeeImpl =
                (EmployeeImpl) context.getBean("employeeImpl");


        if (employeeImpl.validateEmployeeDetails(employee)) {

            employeeImpl.addEmployee(employee);
            employee.setSuccessMessage("Employee added successfully");

        }else{

            employee.setErrorMessage("employee detail insertion failed due to invalid" +
                    " inputs, please recheck inputs and retry");

            return Response.ok().status(Response.Status.BAD_REQUEST)
                    .entity(employee)
                    .header("Access-Control-Allow-Origin", "*")

                    .header("Access-Control-Allow-Methods", "POST, OPTIONS")
                    .header("Access-Control-Allow-Headers","Content-Type")
                    .build();

        }


        return Response.ok()
                .entity(employee)
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "POST, OPTIONS")
                .header("Access-Control-Allow-Headers","Content-Type")
                .build();


    } 

Maven dependencies:

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.18.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-grizzly2</artifactId>
            <version>1.8</version>
        </dependency>

Request headers:

Host: localhost:9091
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Upvotes: 1

Views: 474

Answers (1)

krezus
krezus

Reputation: 1451

If it is your Test application, you can use Allow-Control-Allow-Origin chrome extension to enable allow cross request.

The problem is about using 8080 and 9091 port at the same time.

Host: localhost:9091 
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:8080

and check this

Update:

reason to having this problem is I haven't registered the CORSFilter in grizzle server, after register the CORSFilter in grizzle able to solve the problem as following way

need to create a CORSFilter class as following way

public class CORSFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest request,
                                ContainerResponse response) {

    response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
    response.getHttpHeaders().add("Access-Control-Allow-Headers",
            "origin, content-type, accept, authorization," +
                    "access-control-allow-origin," +
                    "Access-Control-Allow-Credentials");
    response.getHttpHeaders().add("Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS");

    response.getHttpHeaders().add("Access-Control-Expose-Headers","authorization,errorMessage,successMessage");


    return response;
   }
}

register the CORSFilter

ResourceConfig rc=new PackagesResourceConfig("hms.test.automation.system.tc.manager.resources"); // register resources
    // Packages and exception mappers

    rc.getContainerResponseFilters().add(CORSFilter.class);

Upvotes: 1

Related Questions